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

      <q-card-section>
        <div class="text-body2 q-mb-sm">Dados da Unidade</div>

        <div class="row q-col-gutter-x-sm">
          <DefaultInput
            :model-value="unitData.id"
            class="col-md-3 col-12"
            color="secondary"
            disable
            label="ID"
            label-color="secondary"
          />

          <DefaultInput
            :model-value="unitData.franchisee_name"
            class="col-md-3 col-12"
            color="secondary"
            disable
            label="Nome do Franqueado"
            label-color="secondary"
          />

          <DefaultInput
            :model-value="unitData.franchisee_document"
            class="col-md-3 col-12"
            color="secondary"
            disable
            label="CPF/CNH"
            label-color="secondary"
          />

          <DefaultInput
            :model-value="unitData.franchisee_birthday"
            class="col-md-3 col-12"
            color="secondary"
            disable
            label="Data de Nascimento"
            label-color="secondary"
          />
        </div>
      </q-card-section>

      <q-card-section>
        <div class="text-body2 q-mb-sm">Definir Valores e TBR</div>

        <div class="row q-col-gutter-sm">
          <DefaultInputDatePicker
            v-model:untreated-date="contractForm.start_date"
            class="col-md-3 col-12"
            color="secondary"
            label="Data de Início"
            label-color="secondary"
          />

          <DefaultInputDatePicker
            v-model:untreated-date="contractForm.end_date"
            class="col-md-3 col-12"
            color="secondary"
            label="Data de Fim"
            label-color="secondary"
          />

          <DefaultCurrencyInput
            v-model="contractForm.tbr_fixed_value"
            class="col-md-3 col-12"
            color="secondary"
            label="TBR $"
            label-color="secondary"
          />

          <DefaultInput
            v-model="contractForm.invoice_due_date"
            class="col-md-3 col-12"
            color="secondary"
            label="Dia de Vencimento do Boleto"
            label-color="secondary"
            type="number"
          >
          </DefaultInput>

          <DefaultSelect
            v-model="contractForm.inhabitant_classification_id"
            class="col-md-3 col-12"
            color="secondary"
            emit-value
            fill-input
            hide-selected
            input-debounce="0"
            label="Faixa de Habitante"
            label-color="secondary"
            map-options
            use-input
            :options="inhabitantOptions"
          />

          <DefaultInput
            v-model="contractForm.tax_base_royalts"
            class="col-md-3 col-12"
            color="secondary"
            label="Taxa Base Royalties"
            label-color="secondary"
            type="number"
          >
            <template #append>
              <span class="text-secondary">%</span>
            </template>
          </DefaultInput>

          <DefaultInput
            v-model="contractForm.tax_base_fnm"
            class="col-md-3 col-12"
            color="secondary"
            label="Taxa Base FMN"
            label-color="secondary"
            type="number"
          >
            <template #append>
              <span class="text-secondary">%</span>
            </template>
          </DefaultInput>

          <DefaultInput
            v-model="contractForm.tax_base_maintenance"
            class="col-md-3 col-12"
            color="secondary"
            label="Taxa Base Manutenção"
            label-color="secondary"
            type="number"
          >
            <template #append>
              <span class="text-secondary">%</span>
            </template>
          </DefaultInput>
        </div>
      </q-card-section>

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

<script setup>
import { createFranchiseeContract } from "src/api/franchisee_contract";
import { getInhabitantClassificationsForSelect } from "src/api/inhabitant_classification";
import { getLatestTbr } from "src/api/tbr";
import { getUnit } from "src/api/unit";
import { onMounted, reactive, ref } from "vue";
import { useDialogPluginComponent } from "quasar";

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

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

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

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

const saving = ref(false);

const inhabitantOptions = ref([]);

const unitData = reactive({
  id: null,
  franchisee_birthday: null,
  franchisee_document: null,
  franchisee_name: null,
});

const contractForm = reactive({
  end_date: null,
  inhabitant_classification_id: null,
  invoice_due_date: null,
  start_date: null,
  tax_base_fnm: null,
  tax_base_maintenance: null,
  tax_base_royalts: null,
  tbr_fixed_value: null,
});

async function loadData() {
  const [unit, latestTbr, classifications] = await Promise.all([
    getUnit(props.unitId),
    getLatestTbr(),
    getInhabitantClassificationsForSelect(),
  ]);

  unitData.id = unit.id;

  unitData.franchisee_name = unit.name_responsible;

  const firstPartner = unit.partners?.[0];

  if (firstPartner) {
    unitData.franchisee_document = firstPartner.cpf;
    unitData.franchisee_birthday = firstPartner.birth_date;
  }

  if (latestTbr) {
    contractForm.tbr_fixed_value = parseFloat(latestTbr.tbr_value);

    contractForm.tax_base_royalts = parseFloat(
      (latestTbr.royalties_percentage * 100).toFixed(4),
    );

    contractForm.tax_base_fnm = parseFloat(
      (latestTbr.fnm_percentage * 100).toFixed(4),
    );

    contractForm.tax_base_maintenance = parseFloat(
      (latestTbr.maintenance_percentage * 100).toFixed(4),
    );
  }

  inhabitantOptions.value = classifications.map((c) => ({
    label: `${c.description} (${c.acronym})`,
    value: c.id,
  }));
}

async function save() {
  saving.value = true;

  try {
    await createFranchiseeContract({
      unit_id: props.unitId,
      start_date: contractForm.start_date,
      end_date: contractForm.end_date,
      tbr_fixed_value: contractForm.tbr_fixed_value,
      invoice_due_date: contractForm.invoice_due_date,
      inhabitant_classification_id: contractForm.inhabitant_classification_id,

      tbr_fixed_value_percentage:
        contractForm.tax_base_royalts != null
          ? contractForm.tax_base_royalts / 100
          : null,

      marketing_fund_percentage:
        contractForm.tax_base_fnm != null
          ? contractForm.tax_base_fnm / 100
          : null,

      maintance_tax_percentage:
        contractForm.tax_base_maintenance != null
          ? contractForm.tax_base_maintenance / 100
          : null,
    });
    onDialogOK();
  } catch (error) {
    console.error(error);
  } finally {
    saving.value = false;
  }
}

onMounted(loadData);
</script>
