<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="q-dialog-plugin overflow-hidden"
      style="width: 100%; max-width: 1350px"
    >
      <DefaultDialogHeader title="Visualizar Contrato" @close="onDialogCancel" />

      <template v-if="loading">
        <q-card-section style="height: 65vh" class="flex flex-center">
          <q-spinner size="40px" color="primary" />
        </q-card-section>
      </template>

      <template v-else-if="contract">
        <q-tabs
          v-model="activeTab"
          dense
          align="left"
          class="q-px-md text-grey-7"
          active-color="primary"
          indicator-color="primary"
        >
          <q-tab name="dados" label="Dados do Contrato" />
          <q-tab name="midias" label="Mídias do Contrato" />
        </q-tabs>
        <q-separator />

        <q-card-section class="q-pt-sm" style="height: 65vh; overflow-y: auto">
          <div v-show="activeTab === 'dados'">
            <div class="text-subtitle1 q-mb-md">Dados do Aluno</div>

            <div class="row q-col-gutter-sm">
              <div class="col-12">
                <DefaultInput :model-value="contract.student_name" label="Aluno" disable />
              </div>

              <div class="col-6">
                <DefaultInput :model-value="contract.student_document" label="CPF" disable />
              </div>

              <div class="col-6">
                <DefaultInput :model-value="contract.student_birth_date" label="Data de Nascimento" disable />
              </div>
            </div>

            <div class="text-subtitle1 q-mt-lg q-mb-md">Dados do Contrato</div>

            <div class="row q-col-gutter-sm">
              <div class="col-4">
                <DefaultInput :model-value="contract.protocol" label="Protocolo" disable />
              </div>

              <div class="col-4">
                <DefaultInput :model-value="contract.signature_date" label="Data Assinatura" disable />
              </div>

              <div class="col-4">
                <DefaultInput :model-value="contract.end_date" label="Data Encerramento" disable />
              </div>

              <div class="col-5">
                <DefaultInput :model-value="contract.package_name" label="Pacote de Aulas" disable />
              </div>

              <div class="col-7">
                <DefaultInput :model-value="contract.class_quantity" label="Qtd. Aulas" disable />
              </div>

              <div class="col-4">
                <DefaultInput :model-value="weekdayLabel(contract.weekday)" label="Dia da Semana" disable />
              </div>

              <div class="col-4">
                <DefaultInput :model-value="contract.start_time" label="Hora de Início" disable>
                  <template #append><q-icon name="mdi-clock-outline" /></template>
                </DefaultInput>
              </div>

              <div class="col-4">
                <DefaultInput :model-value="contract.end_time" label="Hora de Término" disable>
                  <template #append><q-icon name="mdi-clock-outline" /></template>
                </DefaultInput>
              </div>

              <div class="col-4">
                <DefaultInput :model-value="weekdayLabel(contract.second_weekday)" label="2° Dia da Semana" disable />
              </div>

              <div class="col-4">
                <DefaultInput :model-value="contract.second_start_time" label="Hora de Início" disable>
                  <template #append><q-icon name="mdi-clock-outline" /></template>
                </DefaultInput>
              </div>

              <div class="col-4">
                <DefaultInput :model-value="contract.second_end_time" label="Hora de Término" disable>
                  <template #append><q-icon name="mdi-clock-outline" /></template>
                </DefaultInput>
              </div>
            </div>

            <div class="text-subtitle1 q-mt-lg q-mb-md">Dados Financeiros</div>

            <div class="row q-col-gutter-sm">
              <div class="col-4">
                <DefaultInput :model-value="contract.due_day" label="Dia de Vencimento" disable />
              </div>

              <div class="col-4">
                <DefaultCurrencyInput :model-value="contract.tax_register" label="Taxa de Matrícula" disable />
              </div>

              <div class="col-4">
                <DefaultInput :model-value="contract.class_quantity" label="Total de Aulas" disable />
              </div>

              <div class="col-3">
                <DefaultCurrencyInput :model-value="contract.down_payment" label="Entrada" disable />
              </div>

              <div class="col-3">
                <DefaultInput :model-value="contract.installments ? `${contract.installments}x` : null" label="Parcelas" disable />
              </div>

              <div class="col-6">
                <DefaultInput :model-value="contract.early_payment_discount" label="Desconto até o vencimento (%)" disable />
              </div>

              <div class="col-3">
                <DefaultCurrencyInput :model-value="contract.material_value" label="Valor dos Materiais" disable />
              </div>

              <div class="col-3">
                <DefaultInput :model-value="contract.material_installments ? `${contract.material_installments}x` : null" label="Parcelas" disable />
              </div>

              <div class="col-6">
                <DefaultInput :model-value="contract.interest_rate" label="Juros (%) a.m" disable />
              </div>

              <div class="col-6">
                <DefaultInput :model-value="paymentMethodLabel(contract.payment_method)" label="Forma de Pagamento" disable />
              </div>

              <div class="col-6">
                <DefaultInput :model-value="contract.fine_cancelled" label="Multa (%)" disable />
              </div>
            </div>
          </div>

          <div v-show="activeTab === 'midias'">
            <DefaultTable
              v-model:rows="medias"
              title="Mídias"
              :columns="mediaColumns"
              descricao="mídias"
              :feminino="true"
              no-api-call
              :show-search-field="false"
              :loading="loadingMedias"
            >
              <template #body-cell-actions="{ row }">
                <q-td align="center">
                  <q-btn
                    outline
                    icon="mdi-eye-outline"
                    style="width: 36px"
                    @click.prevent.stop="openFile(row.file_url)"
                  />
                </q-td>
              </template>
            </DefaultTable>
          </div>
        </q-card-section>
      </template>

      <q-separator />

      <q-card-actions align="right">
        <q-btn outline color="primary" label="FECHAR" @click="onDialogCancel" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { useDialogPluginComponent } from "quasar";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultCurrencyInput from "src/components/defaults/DefaultCurrencyInput.vue";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import { getStudentContractById } from "src/api/studentContract";
import { getContractMedias } from "src/api/student_media";

const props = defineProps({
  id: {
    type: Number,
    required: true,
  },
});

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef, onDialogHide, onDialogCancel } = useDialogPluginComponent();

const contract = ref(null);
const loading = ref(false);
const activeTab = ref("dados");
const medias = ref([]);
const loadingMedias = ref(false);

onMounted(async () => {
  loading.value = true;
  try {
    contract.value = await getStudentContractById(props.id);
  } finally {
    loading.value = false;
  }
});

async function fetchMedias() {
  loadingMedias.value = true;
  try {
    medias.value = await getContractMedias(props.id);
  } finally {
    loadingMedias.value = false;
  }
}

watch(activeTab, (tab) => {
  if (tab === "midias") fetchMedias();
});

function openFile(url) {
  window.open(url, "_blank");
}

const mediaColumns = [
  { name: "created_at", label: "Data de Anexo", field: "created_at", align: "left" },
  { name: "actions", label: "Ações", field: null, align: "center" },
];

const weekdays = {
  0: "Domingo",
  1: "Segunda",
  2: "Terça",
  3: "Quarta",
  4: "Quinta",
  5: "Sexta",
  6: "Sábado",
};

const paymentMethods = {
  pix: "Pix",
  credit_card: "Cartão de Crédito",
  debit_card: "Cartão de Débito",
};

function weekdayLabel(value) {
  return value != null ? weekdays[value] ?? null : null;
}

function paymentMethodLabel(value) {
  return value ? paymentMethods[value] ?? value : null;
}
</script>
