<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="q-dialog-plugin overflow-hidden"
      style="width: 100%; max-width: 1100px"
    >
      <DefaultDialogHeader :title="props.contract ? 'Editar Contrato' : 'Novo Contrato'" @close="onDialogCancel" />

      <q-card-section class="q-pt-sm" style="height: 65vh; overflow-y: auto">
        <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="props.student.name"
              label="Aluno"
              disable
            />
          </div>

          <div class="col-6">
            <DefaultInput
              :model-value="props.student.document_number"
              label="CPF"
              disable
            />
          </div>

          <div class="col-6">
            <DefaultInput
              :model-value="formattedBirthDate"
              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 v-model="form.protocol" label="Protocolo" />
          </div>

          <div class="col-4">
            <DefaultInputDatePicker
              v-model="form.signature_date"
              label="Data Assinatura"
            />
          </div>

          <div class="col-4">
            <DefaultInputDatePicker
              v-model="form.end_date"
              label="Data Encerramento"
            />
          </div>

          <div class="col-5">
            <DefaultSelect
              v-model="form.package_id"
              label="Pacote de Aulas"
              :options="packages"
              option-value="id"
              option-label="name"
              emit-value
              map-options
            />
          </div>

          <div class="col-7">
            <DefaultInput
              v-model="form.class_quantity"
              label="Qtd. Aulas"
              type="number"
              disable
            />
          </div>

          <div class="col-4">
            <DefaultSelect
              v-model="form.weekday"
              label="Dia da Semana"
              :options="weekdays"
              option-value="value"
              option-label="label"
              emit-value
              map-options
            />
          </div>

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

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

          <div class="col-4">
            <DefaultSelect
              v-model="form.second_weekday"
              label="2° Dia da Semana"
              :options="weekdays"
              option-value="value"
              option-label="label"
              emit-value
              map-options
            />
          </div>

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

          <div class="col-4">
            <DefaultInput
              v-model="form.second_end_time"
              label="Hora de Término"
              mask="##:##"
            >
              <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">
            <DefaultInputDatePicker
              v-model="form.due_date"
              label="Vencimento"
            />
          </div>

          <div class="col-4">
            <DefaultCurrencyInput
              v-model="form.enrollment_fee"
              label="Taxa de Matrícula"
              disable
            />
          </div>

          <div class="col-4">
            <DefaultInput
              v-model="form.total_classes"
              label="Total de Aulas"
              type="number"
              disable
            />
          </div>

          <div class="col-3">
            <DefaultCurrencyInput
              v-model="form.down_payment"
              label="Entrada"
            />
          </div>

          <div class="col-3">
            <DefaultSelect
              v-model="form.installments"
              label="Parcelas"
              :options="installmentOptions"
              option-value="value"
              option-label="label"
              emit-value
              map-options
            />
          </div>

          <div class="col-6">
            <DefaultInput
              v-model="form.early_payment_discount"
              label="Desconto até o vencimento (%)"
              type="number"
            />
          </div>

          <div class="col-3">
            <DefaultCurrencyInput
              v-model="form.material_value"
              label="Valor dos Materiais"
            />
          </div>

          <div class="col-3">
            <DefaultSelect
              v-model="form.material_installments"
              label="Parcelas"
              :options="installmentOptions"
              option-value="value"
              option-label="label"
              emit-value
              map-options
            />
          </div>

          <div class="col-6">
            <DefaultInput
              v-model="form.interest_rate"
              label="Juros (%) a.m"
              type="number"
            />
          </div>

          <div class="col-6">
            <DefaultSelect
              v-model="form.payment_method"
              label="Forma de Pagamento"
              :options="paymentMethods"
              option-value="value"
              option-label="label"
              emit-value
              map-options
            />
          </div>

          <div class="col-6">
            <DefaultInput
              v-model="form.late_fee"
              label="Multa (%)"
              type="number"
            />
          </div>
        </div>
      </q-card-section>

      <q-separator />

      <q-card-actions align="right">
        <q-btn
          outline
          color="primary"
          label="CANCELAR"
          @click="onDialogCancel"
        />
        <q-btn
          color="primary"
          label="SALVAR"
          :loading="saving"
          @click="handleSave"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { computed, 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 DefaultSelect from "src/components/defaults/DefaultSelect.vue";
import DefaultCurrencyInput from "src/components/defaults/DefaultCurrencyInput.vue";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { formatDateYMDtoDMY, formatDateDMYtoYMD } from "src/helpers/utils";
import { getUnitPackages } from "src/api/package";
import { createStudentContract, updateStudentContract } from "src/api/studentContract";

const props = defineProps({
  student: {
    type: Object,
    required: true,
  },
  contract: {
    type: Object,
    default: null,
  },
});

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

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

const trimTime = (t) => (t ? t.slice(0, 5) : null);

const { form } = useFormUpdateTracker({
  protocol:               props.contract?.protocol ?? null,
  signature_date:         props.contract?.signature_date ?? null,
  end_date:               props.contract?.end_date ?? null,
  package_id:             props.contract?.class_package_unit_id ?? null,
  class_quantity:         props.contract?.class_quantity ?? null,
  weekday:                props.contract?.weekday ?? null,
  start_time:             trimTime(props.contract?.start_time),
  end_time:               trimTime(props.contract?.end_time),
  second_weekday:         props.contract?.second_weekday ?? null,
  second_start_time:      trimTime(props.contract?.second_start_time),
  second_end_time:        trimTime(props.contract?.second_end_time),
  due_date:               props.contract?.due_date ?? null,
  enrollment_fee:         props.contract?.tax_register ?? null,
  total_classes:          props.contract?.class_quantity ?? null,
  down_payment:           props.contract?.down_payment ?? null,
  installments:           props.contract?.installments ?? null,
  early_payment_discount: props.contract?.early_payment_discount ?? null,
  material_value:         props.contract?.material_value ?? null,
  material_installments:  props.contract?.material_installments ?? null,
  interest_rate:          props.contract?.interest_rate ?? null,
  payment_method:         props.contract?.payment_method ?? null,
  late_fee:               props.contract?.fine_cancelled ?? null,
});

const installmentOptions = Array.from({ length: 12 }, (_, i) => ({
  value: i + 1,
  label: `${i + 1}x`,
}));

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

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

const packages = ref([]);

onMounted(async () => {
  packages.value = await getUnitPackages();
});

watch(
  () => form.package_id,
  (id) => {
    const pkg = packages.value.find((p) => p.id === id);
    if (!pkg) return;
    form.class_quantity = pkg.quantity_classes;
    form.total_classes = pkg.quantity_classes;
    form.enrollment_fee = pkg.contract_register_value;
  },
);

const formattedBirthDate = computed(() =>
  props.student.birth_date ? formatDateYMDtoDMY(props.student.birth_date) : "",
);

const { loading: saving, execute } = useSubmitHandler({
  onSuccess: () => onDialogOK(true),
});

function buildPayload() {
  return {
    student_id:              props.student.id,
    protocol:                form.protocol,
    signature_date:          form.signature_date ? formatDateDMYtoYMD(form.signature_date) : null,
    end_date:                form.end_date ? formatDateDMYtoYMD(form.end_date) : null,
    class_package_unit_id:   form.package_id,
    class_quantity:          form.class_quantity,
    weekday:                 form.weekday,
    start_time:              form.start_time,
    end_time:                form.end_time,
    second_weekday:          form.second_weekday,
    second_start_time:       form.second_start_time,
    second_end_time:         form.second_end_time,
    due_date:                form.due_date ? formatDateDMYtoYMD(form.due_date) : null,
    tax_register:            form.enrollment_fee,
    down_payment:            form.down_payment ?? 0,
    installments:            form.installments,
    early_payment_discount:  form.early_payment_discount,
    material_value:          form.material_value,
    material_installments:   form.material_installments,
    interest_rate:           form.interest_rate,
    payment_method:          form.payment_method,
    fine_cancelled:          form.late_fee,
  };
}

async function handleSave() {
  const payload = buildPayload();
  await execute(() =>
    props.contract
      ? updateStudentContract(props.contract.id, payload)
      : createStudentContract(payload),
  );
}
</script>
