<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="q-dialog-plugin overflow-hidden"
      style="width: 100%; max-width: 1200px; height: 100%; max-height: 800px"
    >
      <DefaultDialogHeader title="Ajustes Usuário" @close="onDialogCancel" />

      <div class="q-pa-md" style="height: 100%">
        <div
          class="text-center text-subtitle1 text-weight-bold text-primary"
          style="
            border:        1px solid rgba(0, 0, 0, 0.24);
            width:         100%;
            height:        100%;
            max-height:    660px;
            margin:        auto;
            border-radius: 8px;
          "
        >
          <div class="q-my-md">Dados pessoais</div>

          <div class="row q-col-gutter-sm q-pa-md">
            <q-input
              v-model="form.id"
              class="col-2"
              disable
              label="N. Registro"
            />

            <q-input
              v-model="form.name"
              class="col-6"
              label="Nome"
              :rules="[inputRules.required]"
            />

            <q-input
              v-model="form.document_number"
              class="col-4"
              disable
              label="CPF"
              :mask="masks.Brasil.cpf"
              :rules="[inputRules.required]"
            />

            <DefaultPasswordInput
              v-model="form.password"
              class="col-3"
              label="Senha"
            />

            <DefaultPasswordInput
              v-model="form.password_confirmation"
              class="col-3"
              label="Confirmar senha"
            />

            <q-select
              v-model="userTypeSelected"
              class="col-3"
              disable
              label="Tipo de Usuario"
              map-options
              :options="userTypeSelect"
              :rules="[inputRules.required]"
            />
          </div>
        </div>

        <q-card-actions align="right" class="q-mt-md q-pa-none">
          <q-btn
            color="primary"
            label="Cancelar"
            outline
            padding="10px 30px"
            style="border-radius: 8px"
            @click="onDialogCancel"
          />

          <q-btn
            color="primary"
            label="Salvar"
            padding="10px 40px"
            style="border-radius: 8px"
            :disable="!hasUpdatedFields"
            :loading="loading"
            @click="onSubmit"
          />
        </q-card-actions>
      </div>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { getUserById, updateUser } from "src/api/user";
import { useDialogPluginComponent } from "quasar";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useInputRules } from "src/composables/useInputRules";

import masks from "src/helpers/masks";

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

const { inputRules } = useInputRules();

const { userId } = defineProps({
  userId: { type: Number, default: null, required: true },
});

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

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

const { form, hasUpdatedFields, setUpdateFormAsOriginal, getUpdatedFields } =
  useFormUpdateTracker({
    id:              null,
    name:            null,
    document_number: null,
    password:        null,
    user_type:       null,
    password_confirmation: null,
  });

const userTypeSelected = ref(null);

const loading = ref(false);

const userTypeSelect = ref([
  { label: "Administrador", value: 1 },
  { label: "Convidado",     value: 2 },
  { label: "Proprietario",  value: 3 },
  { label: "Recepcionista", value: 4 },
  { label: "Cliente",       value: 5 },
  { label: "Prestador",     value: 6 },
  { label: "Gerente",       value: 7 },
  { label: "Agente",        value: 8 },
]);

const requiredInputs = computed(() => {
  return form.name && form.document_number && form.user_type;
});

const fetchUser = async () => {
  try {
    const userData = await getUserById(userId);

    Object.assign(form, userData);

    setUpdateFormAsOriginal();

    userTypeSelected.value = userData.user_type;
  } catch (error) {
    console.error("Falha ao buscar dados do usuário:", error);
  }
};

const onSubmit = async () => {
  try {
    if (!requiredInputs.value) {
      return;
    }

    loading.value = true;

    const payload = getUpdatedFields.value;

    await updateUser(payload, userId);

    onDialogOK();
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

onMounted(fetchUser);
</script>
