<template>
  <div class="financial-tab q-pa-md">
    <DefaultForm ref="formRef" class="unit-tab-form" @submit="onSave">
      <q-scroll-area ref="scrollAreaRef" class="unit-form-tab-scroll-area">
        <div class="column q-gutter-lg">
          <div>
            <div class="text-subtitle1 text-weight-medium q-mb-sm">
              Dados Bancários
            </div>

            <div class="row q-col-gutter-md">
              <DefaultInput
                v-model="form.account_holder"
                v-model:error="validationErrors.account_holder"
                class="col-12 col-md-4"
                label="Titular da Conta"
                outlined
                :error-message="validationErrors.account_holder"
              />

              <DefaultInput
                v-model="form.agency"
                v-model:error="validationErrors.agency"
                class="col-12 col-md-4"
                label="Agência"
                outlined
                :error-message="validationErrors.agency"
              />

              <DefaultInput
                v-model="form.account"
                v-model:error="validationErrors.account"
                class="col-12 col-md-4"
                label="Conta"
                outlined
                :error-message="validationErrors.account"
              />

              <DefaultInput
                v-model="form.bank"
                v-model:error="validationErrors.bank"
                class="col-12 col-md-3"
                label="Banco"
                outlined
                :error-message="validationErrors.bank"
              />

              <DefaultInput
                v-model="form.pix_key"
                v-model:error="validationErrors.pix_key"
                class="col-12 col-md-3"
                label="Chave Pix"
                outlined
                :error-message="validationErrors.pix_key"
              />

              <DefaultSelect
                v-model="form.tax_regime"
                v-model:error="validationErrors.tax_regime"
                class="col-12 col-md-3"
                emit-value
                label="Regime Tributário"
                map-options
                outlined
                :error-message="validationErrors.tax_regime"
                :options="taxRegimeOptions"
              />

              <DefaultSelect
                v-model="form.account_type"
                v-model:error="validationErrors.account_type"
                class="col-12 col-md-3"
                emit-value
                label="Tipo de Conta"
                map-options
                outlined
                :error-message="validationErrors.account_type"
                :options="accountTypeOptions"
              />
            </div>
          </div>

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

            <div class="row q-col-gutter-md">
              <DefaultSelect
                v-model="form.billing_method"
                v-model:error="validationErrors.billing_method"
                class="col-12 col-md-6"
                emit-value
                label="Forma de Cobrança"
                map-options
                outlined
                :error-message="validationErrors.billing_method"
                :options="billingMethodOptions"
              />

              <DefaultInputDatePicker
                v-model="form.due_date"
                v-model:error="validationErrors.due_date"
                class="col-12 col-md-6"
                label="Data de Vencimento"
                :error-message="validationErrors.due_date"
              />

              <DefaultInput
                v-model="form.financial_email"
                v-model:error="validationErrors.financial_email"
                class="col-12"
                label="E-mail Financeiro"
                outlined
                :error-message="validationErrors.financial_email"
                :rules="[inputRules.email]"
              />
            </div>
          </div>

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

            <div class="row q-col-gutter-md">
              <DefaultInput
                v-model.number="form.max_freeze_count"
                v-model:error="validationErrors.max_freeze_count"
                class="col-12 col-md-4"
                label="Máximo de Meses para Trancar"
                outlined
                type="number"
                :error-message="validationErrors.max_freeze_count"
                :rules="[inputRules.minValue(0)]"
              />

              <DefaultInput
                v-model.number="form.default_discount"
                v-model:error="validationErrors.default_discount"
                class="col-12 col-md-4"
                label="Desconto Padrão (%)"
                outlined
                type="number"
                :error-message="validationErrors.default_discount"
                :rules="[inputRules.minValue(0), inputRules.maxValue(100)]"
              />

              <DefaultInput
                v-model.number="form.default_interest"
                v-model:error="validationErrors.default_interest"
                class="col-12 col-md-4"
                label="Juros Padrão (% a.m.)"
                outlined
                type="number"
                :error-message="validationErrors.default_interest"
                :rules="[inputRules.minValue(0)]"
              />

              <DefaultInput
                v-model.number="form.default_fine"
                v-model:error="validationErrors.default_fine"
                class="col-12 col-md-4"
                label="Multa Padrão (%)"
                outlined
                type="number"
                :error-message="validationErrors.default_fine"
                :rules="[inputRules.minValue(0), inputRules.maxValue(100)]"
              />

              <div class="col-12 col-md-4 flex items-center">
                <q-toggle
                  v-model="form.charge_roi"
                  color="primary"
                  label="Cobrar ROI"
                />
              </div>

              <div class="col-12 col-md-4 flex items-center">
                <q-toggle
                  v-model="form.charge_fnm"
                  color="primary"
                  label="Cobrar FNM"
                />
              </div>
            </div>
          </div>
        </div>
      </q-scroll-area>

      <q-separator />

      <div class="row justify-end q-gutter-sm q-pt-md">
        <q-btn
          color="negative"
          label="Cancelar"
          no-caps
          outline
          @click="resetForm"
        />

        <q-btn
          color="primary"
          label="Salvar"
          no-caps
          type="submit"
          unelevated
          :loading="loading"
        />
      </div>
    </DefaultForm>
  </div>
</template>

<script setup>
import {
  getFinancialByUnit,
  upsertFinancial,
} from "src/api/unit_financial";

import { onMounted, ref } from "vue";
import { useForm } from "src/composables/useForm";
import { useInputRules } from "src/composables/useInputRules";
import { useScroll } from "src/composables/useScroll";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

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

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

const { inputRules } = useInputRules();

const { scrollToComponent } = useScroll();

const formRef = ref(null);
const scrollAreaRef = ref(null);

const { form, getUpdatedFields, resetUpdateForm, setUpdateFormAsOriginal } =
  useForm(
    {
      account: null,
      account_holder: null,
      account_type: null,
      agency: null,
      bank: null,
      billing_method: null,
      charge_fnm: true,
      charge_roi: true,
      default_discount: null,
      default_fine: null,
      default_interest: null,
      due_date: null,
      financial_email: null,
      max_freeze_count: null,
      pix_key: null,
      tax_regime: null,
    },
    { containerRef: scrollAreaRef },
  );

const {
  loading,
  validationErrors,
  execute,
} = useSubmitHandler({
  containerRef: scrollAreaRef,
  formRef,
  onSuccess: (saved) => {
    Object.assign(form, saved);
    setUpdateFormAsOriginal();
  },
  scrollFn: scrollToComponent,
});

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 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 fetchData = async () => {
  if (!props.unitId) return;

  await loadFinancial();
};

const loadFinancial = async () => {
  try {
    const data = await getFinancialByUnit(props.unitId);

    if (data) {
      Object.assign(form, data);
      setUpdateFormAsOriginal();
    }
  } catch (error) {
    console.error(error);
  }
};

const onSave = async () => {
  if (!props.unitId) return;

  await execute(() =>
    upsertFinancial({
      unit_id: props.unitId,
      ...getUpdatedFields.value,
    }),
  );
};

const resetForm = () => {
  resetUpdateForm();
};

onMounted(fetchData);
</script>

<style scoped>
.financial-tab {
  box-sizing: border-box;
  min-height: 0;
}

.unit-tab-form {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

.unit-form-tab-scroll-area {
  flex: 1 1 auto;
  min-height: 0;
}
</style>