<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden" style="width: 900px; max-width: 95vw">
      <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')"
            :placeholder="$t('user.profile.name_and_surname')"
            class="col-md-8 col-12 input-violet"
          />
          <DefaultSelect
            v-model="form.status"
            v-model:error="validationErrors.status"
            :options="statusOptions"
            :label="$t('common.terms.status')"
            emit-value
            map-options
            class="col-md-4 col-12"
          />
          <DefaultInput
            v-model="form.email"
            v-model:error="validationErrors.email"
            :rules="[inputRules.email, inputRules.required]"
            :label="$t('common.terms.email')"
            :placeholder="$t('common.placeholders.email')"
            class="col-md-8 col-12"
          />
          <DefaultInput
            v-model="form.cpf"
            v-model:error="validationErrors.cpf"
            :label="$t('common.terms.cpf')"
            :placeholder="$t('common.placeholders.cpf')"
            :mask="'###.###.###-##'"
            class="col-md-4 col-12"
          />
          <DefaultInput
            v-model="form.registration"
            v-model:error="validationErrors.registration"
            :label="$t('associado.registration')"
            :placeholder="$t('common.placeholders.registration')"
            class="col-md-4 col-12"
          />
          <PositionSelect
            v-model="selectedPosition"
            v-model:error="validationErrors.position_id"
            class="col-md-4 col-12"
          />
          <SectorSelect
            v-model="selectedSector"
            v-model:error="validationErrors.sector_id"
            class="col-md-4 col-12"
          />
          <DefaultInputDatePicker
            v-model:untreated-date="form.admission_date"
            v-model:error="validationErrors.admission_date"
            :label="$t('associado.admission_date')"
            class="col-md-6 col-12"
          />
          <DefaultInputDatePicker
            v-model:untreated-date="form.expiry_date"
            v-model:error="validationErrors.expiry_date"
            :label="$t('associado.validity')"
            class="col-md-6 col-12"
          />
          <DefaultPasswordInput
            v-model="form.password"
            v-model:error="validationErrors.password"
            :rules="associado ? [inputRules.password] : [inputRules.required, inputRules.password]"
            :label="$t('common.terms.password')"
            :placeholder="$t('auth.password_hint')"
            class="col-md-6 col-12"
          />
          <DefaultPasswordInput
            v-model="confirmPassword"
            :rules="
              associado
                ? [inputRules.samePassword(form.password)]
                : [inputRules.required, inputRules.samePassword(form.password)]
            "
            :label="$t('auth.confirm_password')"
            class="col-md-6 col-12"
          />
        </q-card-section>
        <q-card-actions>
          <q-space />
          <q-btn
            outline
            color="negative"
            :label="$t('common.actions.cancel')"
            @click="onDialogCancel"
          />
          <q-btn
            color="violet-normal"
            :label="associado ? $t('common.actions.save') : $t('common.actions.add')"
            type="submit"
            :loading="loading"
            :disable="!hasUpdatedFields"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, computed, useTemplateRef, watch } from "vue";
import { useInputRules } from "src/composables/useInputRules";
import { useDialogPluginComponent } from "quasar";
import { useI18n } from "vue-i18n";
import { createUser, updateUser } from "src/api/user";
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 DefaultPasswordInput from "src/components/defaults/DefaultPasswordInput.vue";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";
import PositionSelect from "src/components/selects/PositionSelect.vue";
import SectorSelect from "src/components/selects/SectorSelect.vue";

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

const { associado, title } = defineProps({
  associado: {
    type: Object,
    default: null,
  },
  title: {
    type: Function,
    default: () => useI18n().t("common.actions.add"),
  },
});

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

const selectedPosition = ref(
  associado?.position ? { label: associado.position.name, value: associado.position.id } : null,
);
const selectedSector = ref(
  associado?.sector ? { label: associado.sector.name, value: associado.sector.id } : null,
);

const statusOptions = computed(() => [
  { label: t("common.status.active"),   value: "active" },
  { label: t("common.status.inactive"), value: "inactive" },
  { label: t("common.status.pending"),  value: "pending" },
  { label: t("common.status.on_leave"), value: "on_leave" },
]);

const { form, getUpdatedFields, hasUpdatedFields } = useFormUpdateTracker({
  name:           associado?.name           ?? "",
  email:          associado?.email          ?? "",
  cpf:            associado?.cpf            ?? "",
  registration:   associado?.registration   ?? "",
  password:       "",
  type:           "associado",
  status:         associado?.status         ?? "active",
  position_id:    associado?.position_id    ?? null,
  sector_id:      associado?.sector_id      ?? null,
  admission_date: associado?.admission_date ?? null,
  expiry_date:    associado?.expiry_date     ?? null,
});

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

watch(selectedPosition, (val) => {
  form.position_id = val?.value ?? null;
});

watch(selectedSector, (val) => {
  form.sector_id = val?.value ?? null;
});

const onOKClick = async () => {
  if (associado) {
    await submitForm(() => updateUser(getUpdatedFields.value, associado.id));
  } else {
    await submitForm(() => createUser({ ...form }));
  }
};
</script>
