<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="q-dialog-plugin overflow-hidden"
      style="width: 100%; max-width: 500px"
    >
      <DefaultDialogHeader
        :title="item ? 'Editar Faixa de Habitante' : 'Nova Faixa de Habitante'"
        @close="onDialogCancel"
      />

      <q-form ref="formRef" @submit="onOKClick">
        <q-card-section class="row q-col-gutter-sm q-pt-none">
          <DefaultInput
            v-model="form.description"
            v-model:error="validationErrors.description"
            class="col-12"
            label="Descrição"
            :error-message="validationErrors.description"
            :rules="[inputRules.required]"
          />

          <DefaultInput
            v-model="form.start"
            v-model:error="validationErrors.start"
            class="col-6"
            label="Início"
            min="1"
            type="number"
            :error-message="validationErrors.start"
            :rules="[inputRules.required]"
          />

          <DefaultInput
            v-model="form.end"
            v-model:error="validationErrors.end"
            class="col-6"
            label="Fim"
            min="1"
            type="number"
            :error-message="validationErrors.end"
            :rules="[inputRules.required]"
          />

          <DefaultInput
            v-model="form.tbr_percentage"
            v-model:error="validationErrors.tbr_percentage"
            class="col-12"
            label="Porcentagem de Royalties"
            min="0"
            step="0.01"
            type="number"
            :error-message="validationErrors.tbr_percentage"
            :rules="[
              (v) =>
                (v !== null && v !== undefined && v !== '') ||
                $t('validation.rules.required'),
            ]"
          />
        </q-card-section>

        <q-card-actions>
          <q-space />

          <q-btn
            color="negative"
            label="Cancelar"
            outline
            @click="onDialogCancel"
          />

          <q-btn
            color="primary-2"
            label="Salvar"
            type="submit"
            :loading="loading"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import {
  createInhabitantClassification,
  updateInhabitantClassification,
} from "src/api/inhabitant_classification";

import { useDialogPluginComponent } from "quasar";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { useTemplateRef } from "vue";

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

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

const { item } = defineProps({
  item: {
    type: Object,
    default: null,
  },
});

const { inputRules } = useInputRules();

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

const formRef = useTemplateRef("formRef");

const { form, getUpdatedFields } = useFormUpdateTracker({
  description: item?.description ?? "",
  start: item?.start ?? null,
  end: item?.end ?? null,
  tbr_percentage: item ? Number(item.tbr_percentage) * 100 : null,
});

const { loading, validationErrors, execute } = useSubmitHandler({
  formRef,
  onSuccess: () => onDialogOK(true),
});

const onOKClick = async () => {
  const payload = {
    description: form.description,
    start: form.start,
    end: form.end,
    tbr_percentage: (form.tbr_percentage ?? 0) / 100,
  };

  if (getUpdatedFields.value.tbr_percentage !== undefined) {
    getUpdatedFields.value.tbr_percentage /= 100;
  }

  if (item) {
    await execute(() =>
      updateInhabitantClassification(item.id, getUpdatedFields.value),
    );
  } else {
    await execute(() => createInhabitantClassification(payload));
  }
};
</script>
