<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <div style="width: 100%; max-width: 520px">
      <q-card class="overflow-hidden" style="width: 100%">
        <DefaultDialogHeader
          :title="isEdit ? 'Editar Grupo' : 'Adicionar Novo Grupo'"
          @close="onDialogCancel"
        />

        <DefaultForm ref="formRef" @submit="onOKClick">
          <q-scroll-area class="form-dialog-scroll-area">
            <q-card-section class="q-pt-sm column q-gutter-y-sm">
              <DefaultInput
                v-model="form.name"
                label="Nome do Grupo"
                outlined
                :rules="[inputRules.required]"
              />

              <q-select
                v-model="form.unit_ids"
                :options="unitOptions"
                label="Unidades"
                label-color="secondary"
                outlined
                multiple
                use-chips
                emit-value
                map-options
                hide-dropdown-icon
                :loading="loadingUnits"
              >
                <template #append>
                  <q-icon name="mdi-chevron-down" color="secondary" />
                </template>
              </q-select>
            </q-card-section>
          </q-scroll-area>

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

<script setup>
import { ref, computed, onMounted } from "vue";
import { useDialogPluginComponent } from "quasar";
import { useInputRules } from "src/composables/useInputRules";
import { getUnitsForSelect } from "src/api/unit";
import { createGroup, updateGroup } from "src/api/group";
import { formatUnitName } from "src/helpers/utils";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";

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

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

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

const { inputRules } = useInputRules();

const formRef = ref(null);
const loading = ref(false);
const loadingUnits = ref(true);
const unitOptions = ref([]);

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

const form = ref({
  name: props.group?.name ?? "",
  unit_ids: props.group?.unit_ids ?? [],
});

onMounted(async () => {
  try {
    const units = await getUnitsForSelect();
    unitOptions.value = units.map((u) => ({
      label: formatUnitName(u),
      value: u.id,
    }));
  } catch (error) {
    console.error("Failed to load units:", error);
  } finally {
    loadingUnits.value = false;
  }
});

const onOKClick = async () => {
  loading.value = true;
  try {
    const payload = {
      name: form.value.name,
      unit_ids: form.value.unit_ids,
    };

    const result = isEdit.value
      ? await updateGroup(props.group.id, payload)
      : await createGroup(payload);

    onDialogOK(result);
  } finally {
    loading.value = false;
  }
};
</script>
