<template>
  <div class="q-pa-md column q-gutter-lg">
    <!-- Dados Bancários -->
    <div>
      <div class="text-subtitle1 text-weight-medium q-mb-sm">
        Dados Bancários
      </div>

      <div class="row q-col-gutter-sm">
        <DefaultInput
          v-model="form.account_holder"
          label="Titular da Conta"
          class="col-12 col-md-4"
          outlined
        />
        <DefaultInput
          v-model="form.agency"
          label="Agência"
          class="col-12 col-md-4"
          outlined
        />
        <DefaultInput
          v-model="form.account"
          label="Conta"
          class="col-12 col-md-4"
          outlined
        />

        <DefaultInput
          v-model="form.bank"
          label="Banco"
          class="col-12 col-md-3"
          outlined
        />
        <DefaultInput
          v-model="form.pix_key"
          label="Chave Pix"
          class="col-12 col-md-3"
          outlined
        />
        <DefaultSelect
          v-model="form.tax_regime"
          label="Regime Tributário"
          :options="taxRegimeOptions"
          class="col-12 col-md-3"
          outlined
          emit-value
          map-options
        />
        <DefaultSelect
          v-model="form.account_type"
          label="Tipo de Conta"
          :options="accountTypeOptions"
          class="col-12 col-md-3"
          outlined
          emit-value
          map-options
        />
      </div>
    </div>

    <!-- Dados para Faturamento -->
    <div>
      <div class="text-subtitle1 text-weight-medium q-mb-sm">
        Dados para Faturamento
      </div>

      <div class="row q-col-gutter-sm">
        <DefaultSelect
          v-model="form.billing_method"
          label="Forma de Cobrança"
          :options="billingMethodOptions"
          class="col-12 col-md-6"
          outlined
          emit-value
          map-options
        />
        <DefaultInputDatePicker
          v-model="form.due_date"
          label="Data de Vencimento"
          class="col-12 col-md-6"
        />
        <DefaultInput
          v-model="form.financial_email"
          label="E-mail Financeiro"
          class="col-12"
          outlined
        />
      </div>
    </div>

    <!-- Contratos -->
    <div>
      <div class="text-subtitle1 text-weight-medium q-mb-sm">
        Contratos
      </div>

      <div class="row q-col-gutter-sm">
        <DefaultInput
          v-model.number="form.max_freeze_count"
          label="Máximo de Meses para Trancar"
          type="number"
          class="col-12 col-md-4"
          outlined
        />
        <DefaultInput
          v-model.number="form.default_discount"
          label="Desconto Padrão (%)"
          type="number"
          class="col-12 col-md-4"
          outlined
        />
        <DefaultInput
          v-model.number="form.default_interest"
          label="Juros Padrão (% a.m.)"
          type="number"
          class="col-12 col-md-4"
          outlined
        />
        <DefaultInput
          v-model.number="form.default_fine"
          label="Multa Padrão (%)"
          type="number"
          class="col-12 col-md-4"
          outlined
        />
        <div class="col-12 col-md-4 flex items-center">
          <q-toggle v-model="form.charge_roi" label="Cobrar ROI" color="primary" />
        </div>
        <div class="col-12 col-md-4 flex items-center">
          <q-toggle v-model="form.charge_fnm" label="Cobrar FNM" color="primary" />
        </div>
      </div>
    </div>

    <!-- Actions -->
    <div class="row justify-end q-gutter-sm">
      <q-btn label="Cancelar" color="primary" outline @click="resetForm" />
      <q-btn
        label="Salvar"
        color="primary-2"
        :loading="saving"
        @click="onSave"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";
import { getFinancialByUnit, upsertFinancial } from "src/api/unit_financial";

const props = defineProps({
  unitId: { type: Number, default: null },
});

const taxRegimeOptions = [
  { label: "Selecione", value: null },
  { label: "Simples Nacional", value: "simples_nacional" },
  { label: "Lucro Presumido", value: "lucro_presumido" },
  { label: "Lucro Real", value: "lucro_real" },
  { label: "MEI", value: "mei" },
];

const accountTypeOptions = [
  { label: "Selecione", value: null },
  { label: "Conta Corrente", value: "corrente" },
  { label: "Conta Poupança", value: "poupanca" },
];

const billingMethodOptions = [
  { label: "Selecione", value: null },
  { label: "Boleto", value: "boleto" },
  { label: "Débito Automático", value: "debit" },
  { label: "PIX", value: "pix" },
  { label: "Cartão de Crédito", value: "credit_card" },
];

const defaultForm = () => ({
  tax_regime: null,
  bank: null,
  agency: null,
  account: null,
  account_type: null,
  account_holder: null,
  pix_key: null,
  billing_method: null,
  due_date: null,
  financial_email: null,
  max_freeze_count: null,
  charge_roi: true,
  charge_fnm: true,
  default_discount: null,
  default_interest: null,
  default_fine: null,
});

const form = ref(defaultForm());
const saving = ref(false);

let originalForm = defaultForm();

async function fetchData() {
  if (!props.unitId) return;
  await loadFinancial();
}

async function loadFinancial() {
  try {
    const data = await getFinancialByUnit(props.unitId);
    if (data) {
      Object.assign(form.value, data);
      originalForm = { ...data };
    }
  } catch (e) {
    console.error(e);
  }
}

async function onSave() {
  if (!props.unitId) return;
  saving.value = true;
  try {
    const saved = await upsertFinancial({
      unit_id: props.unitId,
      ...form.value,
    });
    Object.assign(form.value, saved);
    originalForm = { ...saved };
  } catch (e) {
    console.error(e);
  } finally {
    saving.value = false;
  }
}

function resetForm() {
  Object.assign(form.value, defaultForm(), originalForm);
}

onMounted(fetchData);
</script>
