<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden" style="width: 500px">
      <DefaultDialogHeader :title="title" @close="onDialogCancel" />
      <q-form ref="formRef" @submit="onOKClick">
        <q-card-section class="row q-col-gutter-sm q-pt-none">
          <DefaultInput
            v-model="form.name"
            v-model:error="validationErrors.name"
            :rules="[inputRules.required]"
            :label="$t('common.terms.name')"
            class="col-12"
          />
          <DefaultSelect
            v-model="form.kinship"
            v-model:error="validationErrors.kinship"
            :rules="[inputRules.required]"
            :label="$t('associado.kinship')"
            :options="kinshipOptions"
            emit-value
            map-options
            class="col-12"
          />
          <DefaultFilePicker
            v-if="!dependent"
            v-model="documentFile"
            :rules="[inputRules.required]"
            :error="!!validationErrors.document"
            :error-message="validationErrors.document"
            :label="$t('associado.dependent_document')"
            type="file"
            accept="image/*,application/pdf"
            class="col-12"
          />
          <div v-if="!dependent" class="col-12 text-caption text-grey-7">
            {{ $t("associado.dependent_document_hint") }}
          </div>
        </q-card-section>
        <q-card-actions>
          <q-space />
          <q-btn
            outline
            color="negative"
            :label="$t('common.actions.cancel')"
            @click="onDialogCancel"
          />
          <q-btn
            color="primary"
            :label="dependent ? $t('common.actions.save') : $t('common.actions.add')"
            type="submit"
            :loading="loading"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { computed, ref, useTemplateRef } from "vue";
import { useInputRules } from "src/composables/useInputRules";
import { useDialogPluginComponent } from "quasar";
import { useI18n } from "vue-i18n";
import { createDependent, updateDependent } from "src/api/profile";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

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

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

const { dependent, userId, title } = defineProps({
  dependent: { type: Object, default: null },
  userId: { type: Number, required: true },
  title: { type: Function, default: () => "" },
});

const { t } = useI18n();
const { inputRules } = useInputRules();
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();
const formRef = useTemplateRef("formRef");

const kinshipOptions = computed(() => [
  { label: t("associado.kinship_options.conjuge"), value: "conjuge" },
  { label: t("associado.kinship_options.filho"), value: "filho" },
  { label: t("associado.kinship_options.filha"), value: "filha" },
  { label: t("associado.kinship_options.pai"), value: "pai" },
  { label: t("associado.kinship_options.mae"), value: "mae" },
  { label: t("associado.kinship_options.irmao"), value: "irmao" },
  { label: t("associado.kinship_options.irma"), value: "irma" },
  { label: t("associado.kinship_options.outro"), value: "outro" },
]);

// O documento fica fora do tracker: o File não sobrevive ao deepClone usado no diff.
const documentFile = ref(null);

const { form, getUpdatedFields } = useFormUpdateTracker({
  name: dependent?.name ?? "",
  kinship: dependent?.kinship ?? "",
  responsible_user_id: userId,
});

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

const onOKClick = async () => {
  if (dependent) {
    await submitForm(() => updateDependent(dependent.id, getUpdatedFields.value));
  } else {
    await submitForm(() => createDependent({ ...form, document: documentFile.value }));
  }
};
</script>
