<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card style="min-width: 440px">
      <DefaultDialogHeader :title="dialogTitle" @close="onDialogCancel" />

      <DefaultForm ref="formRef" @submit="onSave">
        <q-card-section class="column q-gutter-md">
          <DefaultInput
            v-model="form.label"
            label="Nome"
            outlined
            autofocus
            :rules="[inputRules.required]"
            @update:model-value="onLabelChange"
          />

          <DefaultInput
            v-model="form.slug"
            label="Código"
            outlined
            hint="Identificador único do grupo. Ex.: FINANCEIRO"
            :rules="[inputRules.required, slugRule]"
            @update:model-value="onSlugTouched"
          />
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            label="Cancelar"
            color="primary"
            outline
            @click="onDialogCancel"
          />
          <q-btn
            label="Salvar"
            color="primary"
            type="submit"
            :loading="loading"
          />
        </q-card-actions>
      </DefaultForm>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { computed, ref, useTemplateRef } from "vue";
import { useDialogPluginComponent } from "quasar";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { createUserType, updateUserType } from "src/api/user_type";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";

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

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

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

const { inputRules } = useInputRules();
const formRef = useTemplateRef("formRef");

const isEdit = computed(() => !!group);

const dialogTitle = computed(() =>
  isEdit.value ? "Editar Grupo de Permissões" : "Novo Grupo de Permissões",
);

const form = ref({
  label: group?.label ?? "",
  slug: group?.slug ?? "",
});

// Ao editar, o código já existe e não deve ser re-derivado do nome.
const slugTouched = ref(isEdit.value);

const toSlug = (value) =>
  (value ?? "")
    .normalize("NFD")
    .replace(/\p{Diacritic}/gu, "")
    .toUpperCase()
    .replace(/[^A-Z0-9]+/g, "_")
    .replace(/^_+|_+$/g, "");

const slugRule = (value) =>
  /^[A-Z0-9_]+$/.test(value ?? "") ||
  "Use apenas letras maiúsculas, números e underline.";

const onLabelChange = (value) => {
  if (!slugTouched.value) {
    form.value.slug = toSlug(value);
  }
};

const onSlugTouched = (value) => {
  slugTouched.value = true;
  form.value.slug = toSlug(value);
};

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

const onSave = async () => {
  const payload = { label: form.value.label, slug: form.value.slug };

  await execute(() =>
    isEdit.value ? updateUserType(group.id, payload) : createUserType(payload),
  );
};
</script>
