<template>
  <div>
    <DefaultHeaderPage :title="isEdit ? 'Editar Usuário' : 'Cadastro de Usuário'" />

    <div class="q-pa-md">
      <q-form ref="formRef">
        <div class="column items-center q-mb-lg">
          <AvatarImageComponent
            ref="avatarRef"
            @update:file="(f) => (avatarFile = f)"
          />
        </div>

        <div class="row q-col-gutter-sm">
          <DefaultInput
            v-model="form.name"
            label="Nome completo"
            class="col-6"
            outlined
            :rules="[inputRules.required]"
          />

          <DefaultInput
            v-model="form.cpf"
            label="CPF"
            class="col-6"
            outlined
            :mask="masks.Brasil.cpf"
            :rules="[inputRules.cpf]"
          />

          <UserTypeSelect
            v-model="form.user_type"
            class="col-6"
            outlined
            label="Função"
            :rules="[inputRules.required]"
            :disable="!canChangeUserType"
            :exclude-types="['ADMIN']"
          />

          <DefaultInput
            v-model="form.phone"
            label="Telefone"
            class="col-6"
            outlined
            :mask="masks.Brasil.celular"
          />

          <DefaultInput
            v-model="form.email"
            label="E-mail"
            class="col-6"
            outlined
            type="email"
            :rules="[inputRules.required, inputRules.email]"
          />

          <DefaultPasswordInput
            v-model="form.password"
            label="Senha"
            class="col-6"
            outlined
            :rules="
              isEdit
                ? [(v) => !v || v.length >= 8 || 'Mínimo 8 caracteres']
                : [inputRules.required, inputRules.min(8)]
            "
          />

          <div v-if="isEdit" class="col-12 text-caption text-grey-6">
            Deixe os campos de senha em branco para manter a senha atual.
          </div>
        </div>

        <div class="row justify-end q-mt-lg q-gutter-sm">
          <q-btn
            label="Cancelar"
            color="primary"
            outline
            @click="router.push({ name: 'UsersPage' })"
          />
          <q-btn
            label="Salvar"
            color="primary"
            :loading="loading"
            @click="onSave"
          />
        </div>
      </q-form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { storeToRefs } from "pinia";
import { useQuasar } from "quasar";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultPasswordInput from "src/components/defaults/DefaultPasswordInput.vue";
import AvatarImageComponent from "src/components/shared/AvatarImageComponent.vue";
import UserTypeSelect from "src/components/selects/UserTypeSelect.vue";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { createUser, updateUser, getUserById } from "src/api/user";
import { userStore } from "src/stores/user";
import masks from "src/helpers/masks";

const router = useRouter();
const route = useRoute();
const $q = useQuasar();
const { inputRules } = useInputRules();
const store = userStore();
const { user } = storeToRefs(store);

const formRef = ref(null);
const avatarRef = ref(null);
const avatarFile = ref(null);
const originalUserType = ref(null);

const isEdit = computed(() => !!route.params.id);
const isEditingSelf = computed(() => isEdit.value && parseInt(route.params.id) === user.value?.id);
const canChangeUserType = computed(() => user.value?.user_type === "ADMIN_FRANCHISEE");

const form = ref({
  name: null,
  cpf: null,
  phone: null,
  user_type: null,
  email: null,
  password: null,
});

const { loading, execute } = useSubmitHandler({
  formRef,
  onSuccess: () => router.push({ name: "UsersPage" }),
});

onMounted(async () => {
  if (!isEdit.value) return;
  try {
    const data = await getUserById(route.params.id);
    form.value.name = data.name;
    form.value.email = data.email;
    form.value.cpf = data.cpf;
    form.value.phone = data.phone;
    form.value.user_type = data.user_type;
    originalUserType.value = data.user_type;
    if (data.avatar_url) avatarRef.value?.setImageUrl(data.avatar_url);
  } catch (error) {
    console.error("Failed to load user:", error);
  }
});

function buildPayload() {
  const fd = new FormData();

  if (avatarFile.value) fd.append("avatar", avatarFile.value);

  if (store.selectedUnit?.id) fd.append("unit_id", store.selectedUnit.id);
  if (form.value.user_type) fd.append("user_type", form.value.user_type);
  if (form.value.cpf) fd.append("cpf", form.value.cpf);
  if (form.value.phone) fd.append("phone", form.value.phone);
  if (form.value.name) fd.append("name", form.value.name);
  if (form.value.email) fd.append("email", form.value.email);
  if (form.value.password) fd.append("password", form.value.password);

  return fd;
}

async function onSave() {
  if (isEditingSelf.value && form.value.user_type !== originalUserType.value) {
    $q.notify({
      type: "warning",
      message: "Não é possível alterar o seu próprio tipo de usuário. Entre em contato com o suporte.",
    });
    return;
  }

  if (isEdit.value) {
    await execute(() => updateUser(buildPayload(), route.params.id));
  } else {
    await execute(() => createUser(buildPayload()));
  }
}
</script>
