<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">
              Contratos
            </div>

            <div class="row q-col-gutter-md">
              <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>

              <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)]"
              />
            </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";

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(
    {
      charge_fnm: true,
      charge_roi: true,
      max_freeze_count: null,
    },
    { containerRef: scrollAreaRef },
  );

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

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>
