<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="dialog-form-card"
      style="min-width: 440px; max-width: 90vw"
    >
      <DefaultDialogHeader
        :title="
          isEdit
            ? 'Editar Grupo de Permissões'
            : 'Novo Grupo de Permissões'
        "
        @close="onDialogCancel"
      />

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

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

        <q-card-actions
          align="right"
          class="q-px-md q-pb-md"
        >
          <q-btn
            color="primary"
            label="Cancelar"
            no-caps
            outline
            @click="onDialogCancel"
          />

          <q-btn
            color="secondary"
            label="Salvar"
            no-caps
            type="submit"
            :loading="loading"
          />
        </q-card-actions>
      </DefaultForm>
    </q-card>
  </q-dialog>
</template>

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

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

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

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

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

const { inputRules } = useInputRules();

const formRef = useTemplateRef("formRef");

const slugTouched = ref(!!group);

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

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

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

const onLabelChange = (value) => {
  if (slugTouched.value) return;

  form.slug = toSlug(value);
};

const onSave = () =>
  execute(() => {
    if (isEdit.value) {
      return updateUserType(
        group.id,
        { ...getUpdatedFields.value },
      );
    }

    return createUserType({ ...form });
  });

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

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

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

<style scoped>
.permission-group-fields {
  min-height: 220px;
}
</style>