<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
          class="flex flex-center"
          style="height: 65vh"
        >
          <q-spinner
            color="primary"
            size="40px"
          />
        </q-card-section>
      </template>

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

          <q-tab
            label="Mídias do Contrato"
            name="midias"
          />
        </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"
                  disable
                  label="Aluno"
                />
              </div>

              <div class="col-6">
                <DefaultInput
                  :model-value="contract.student_document"
                  :mask="masks.Brasil.cpf"
                  :rules="[inputRules.cpf]"
                  disable
                  label="CPF"
                />
              </div>

              <div class="col-6">
                <DefaultInput
                  :model-value="contract.student_birth_date"
                  disable
                  label="Data de Nascimento"
                />
              </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"
                  disable
                  label="Protocolo"
                />
              </div>

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

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

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

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

              <div class="col-6">
                <DefaultCurrencyInput
                  :model-value="contract.package_value"
                  disable
                  label="Total do Contrato"
                />
              </div>

              <div class="col-6">
                <DefaultInput
                  :model-value="contractWeeks"
                  disable
                  label="Total de Semanas"
                />
              </div>

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

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

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

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

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

              <div class="col-4">
                <DefaultInput
                  :model-value="contract.second_end_time"
                  disable
                  label="Hora de Término"
                >
                  <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"
                  disable
                  label="Dia de Vencimento"
                />
              </div>

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

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

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

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

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

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

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

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

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

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

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

      <q-card-actions
        align="right"
        class="q-px-md q-pb-md"
      >
        <q-btn
          color="primary"
          label="Fechar"
          no-caps
          outline
          @click="onDialogCancel"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { computed, onMounted, ref, watch } from "vue";

import {
  differenceInCalendarDays,
  isValid,
  parse,
} from "date-fns";

import { getContractMedias } from "src/api/student_media";
import { getStudentContractById } from "src/api/studentContract";
import { useDialogPluginComponent } from "quasar";
import { useInputRules } from "src/composables/useInputRules";

import masks from "src/helpers/masks";

import DefaultCurrencyInput from "src/components/defaults/DefaultCurrencyInput.vue";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultTable from "src/components/defaults/DefaultTable.vue";

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

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

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

const { inputRules } = useInputRules();

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

const contractWeeks = computed(() => {
  if (!contract.value?.signature_date || !contract.value?.end_date) {
    return null;
  }

  const startDate = parse(
    contract.value.signature_date,
    "dd/MM/yyyy",
    new Date(),
  );

  const endDate = parse(
    contract.value.end_date,
    "dd/MM/yyyy",
    new Date(),
  );

  if (!isValid(startDate) || !isValid(endDate)) {
    return null;
  }

  const days = differenceInCalendarDays(
    endDate,
    startDate,
  );

  return days < 0
    ? null
    : Math.max(1, Math.round(days / 7));
});

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

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

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

const fetchMedias = async () => {
  loadingMedias.value = true;

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

const openFile = (url) => {
  window.open(url, "_blank");
};

const paymentMethodLabel = (value) =>
  value ? paymentMethods[value] ?? value : null;

const weekdayLabel = (value) =>
  value != null ? weekdays[value] ?? null : null;

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

onMounted(async () => {
  loading.value = true;

  try {
    contract.value = await getStudentContractById(
      props.id,
    );
  } finally {
    loading.value = false;
  }
});
</script>
