<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="q-dialog-plugin overflow-hidden"
      style="width: 100%; max-width: 1100px"
    >
      <DefaultDialogHeader
        title="Visualizar 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"
            label="ID"
            color="secondary"
            label-color="secondary"
            class="col-md-3 col-12"
            disable
          />

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

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

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

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

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

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

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

        <div class="row q-col-gutter-sm q-mt-xs">
          <DefaultCurrencyInput
            v-model="contractForm.tbr_fixed_value"
            label="TBR $"
            color="secondary"
            label-color="secondary"
            class="col-md-3 col-12"
            disable
          />

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

          <DefaultInput
            v-model="contractForm.tax_base_fnm"
            label="Fundo Nacional de Marketing"
            color="secondary"
            label-color="secondary"
            type="number"
            class="col-md-3 col-12"
            disable
          >
            <template #append>
              <span class="text-secondary">%</span>
            </template>
          </DefaultInput>

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

      <q-card-section>
        <div class="text-body2 q-mb-sm">Histórico de Reajuste de Valores e TBR</div>

        <q-table
          flat
          dense
          :rows="tbrHistory"
          :columns="historyColumns"
          row-key="id"
          :loading="loadingHistory"
          :pagination="{ rowsPerPage: 5 }"
          no-data-label="Nenhum histórico disponível"
        />
      </q-card-section>

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

<script setup>
import { ref, reactive, onMounted } 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";

import { getUnit } from "src/api/unit";
import { getMunicipalitySizes } from "src/api/tbr_calculation";
import { getFranchiseeContractTaxHistory } from "src/api/franchisee_contract";

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

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

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

const loadingHistory = ref(false);
const municipalitySizeOptions = ref([]);
const tbrHistory = ref([]);

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

const contractForm = reactive({
  start_date: props.contract.start_date ?? null,
  end_date: props.contract.end_date ?? null,
  tbr_fixed_value: props.contract.tbr_fixed_value
    ? parseFloat(props.contract.tbr_fixed_value)
    : null,
  invoice_due_date: props.contract.invoice_due_date ?? null,
  municipality_size_id:
    props.contract.municipality_size_id ?? null,
  tax_base_royalts:
    props.contract.tbr_fixed_value_percentage != null
      ? parseFloat((props.contract.tbr_fixed_value_percentage * 100).toFixed(4))
      : null,
  tax_base_fnm:
    props.contract.marketing_fund_percentage != null
      ? parseFloat((props.contract.marketing_fund_percentage * 100).toFixed(4))
      : null,
  tax_base_maintenance:
    props.contract.maintance_tax_percentage != null
      ? parseFloat((props.contract.maintance_tax_percentage * 100).toFixed(4))
      : null,
});

const historyColumns = [
  { name: "id", label: "Id", field: "id", align: "left" },
  {
    name: "year",
    label: "Ano",
    field: (row) => new Date(row.created_at).getFullYear(),
    align: "left",
  },
  {
    name: "municipality_size",
    label: "Faixa de Habitantes",
    field: (row) =>
      row.municipality_size?.description ??
      row.inhabitant_classification?.description ??
      "—",
    align: "left",
  },
  { name: "tbr_fixed_value", label: "TBR", field: "tbr_fixed_value", align: "left" },
  {
    name: "tbr_fixed_value_percentage",
    label: "Royalties",
    field: (row) =>
      row.tbr_fixed_value_percentage != null
        ? `${(row.tbr_fixed_value_percentage * 100).toFixed(0)}%`
        : "-",
    align: "left",
  },
  {
    name: "marketing_fund_percentage",
    label: "FNM",
    field: (row) =>
      row.marketing_fund_percentage != null
        ? `${(row.marketing_fund_percentage * 100).toFixed(0)}%`
        : "-",
    align: "left",
  },
  {
    name: "maintance_tax_percentage",
    label: "Manutenção",
    field: (row) =>
      row.maintance_tax_percentage != null
        ? `${(row.maintance_tax_percentage * 100).toFixed(0)}%`
        : "-",
    align: "left",
  },
];

async function loadData() {
  const [unit, sizes] = await Promise.all([
    getUnit(props.unitId),
    getMunicipalitySizes(),
  ]);

  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;
  }

  municipalitySizeOptions.value = (sizes ?? []).map((s) => ({
    label: s.description,
    value: s.id,
  }));

  loadingHistory.value = true;
  try {
    tbrHistory.value = await getFranchiseeContractTaxHistory(props.contract.id);
  } finally {
    loadingHistory.value = false;
  }
}

onMounted(loadData);
</script>
