<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin dialog-form-card feriados-edit-dialog">
      <DefaultDialogHeader
        :title="dialogTitle"
        @close="onDialogCancel"
      />

      <DefaultForm @submit="save">
        <q-scroll-area class="dialog-form-scroll dialog-form-scroll--sm">
          <q-card-section class="column q-gutter-md q-pt-sm">
            <q-banner
              v-if="isReadOnly"
              class="bg-grey-2 text-grey-7"
              dense
              icon="mdi-lock-outline"
              rounded
            >
              Este feriado foi criado pela franqueadora e não pode ser editado.
            </q-banner>

            <DefaultInput
              v-model="description"
              autofocus
              icon="mdi-pencil-outline"
              label="Nome do Evento"
              outlined
              placeholder="Ex: Ponto facultativo, Natal..."
              :disable="isReadOnly || !canEdit"
              :rules="[inputRules.required]"
            />

            <DefaultSelect
              v-model="type"
              emit-value
              label="Selecione o Tipo."
              map-options
              outlined
              :disable="isReadOnly || !canEdit"
              :options="typeOptions"
            />
          </q-card-section>
        </q-scroll-area>

        <template v-if="isReadOnly || !canEdit">
          <q-card-actions
            align="right"
            class="q-px-md q-pb-md"
          >
            <q-btn
              color="primary"
              label="Fechar"
              no-caps
              outline
              @click="onDialogCancel"
            />
          </q-card-actions>
        </template>

        <template v-else>
          <q-card-actions
            align="between"
            class="q-px-md q-pb-md"
          >
            <q-btn
              v-if="canDelete"
              color="negative"
              label="Excluir"
              no-caps
              outline
              :loading="deleting"
              @click="confirmDelete"
            />

            <div class="row q-gutter-sm">
              <q-btn
                color="primary"
                label="Cancelar"
                no-caps
                outline
                @click="onDialogCancel"
              />

              <q-btn
                color="primary"
                label="Salvar"
                no-caps
                type="submit"
                :disable="!description.trim()"
                :loading="saving"
              />
            </div>
          </q-card-actions>
        </template>
      </DefaultForm>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { computed, ref } from "vue";
import { deleteHoliday, updateHoliday } from "src/api/holiday";
import { permissionStore } from "src/stores/permission";
import { useDialogPluginComponent, useQuasar } from "quasar";
import { useInputRules } from "src/composables/useInputRules";

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

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

const props = defineProps({
  holiday: {
    type: Object,
    required: true,
  },
});

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

const $q = useQuasar();
const { inputRules } = useInputRules();

const permissions = permissionStore();

const deleting = ref(false);
const description = ref(props.holiday.description);
const saving = ref(false);
const type = ref(props.holiday.type ?? "feriado");

const canDelete = computed(() =>
  permissions.getAccess("franchisee_dashboard", "delete"),
);

const canEdit = computed(() =>
  permissions.getAccess("franchisee_dashboard", "edit"),
);

const dialogTitle = computed(() => {
  const [year, month, day] = props.holiday.holiday_date.split("-");

  return `${day}/${month}/${year}`;
});

const isReadOnly = computed(() => !!props.holiday.base_holiday_id);

const typeOptions = [
  {
    label: "Feriado",
    value: "feriado",
  },
  {
    label: "Ponto Facultativo",
    value: "facultativo",
  },
];

const confirmDelete = () => {
  $q.dialog({
    cancel: {
      color: "primary",
      flat: true,
      label: "Cancelar",
    },
    message: `Deseja excluir "${props.holiday.description}"?`,
    ok: {
      color: "negative",
      label: "Excluir",
      unelevated: true,
    },
    title: "Excluir feriado",
  }).onOk(async () => {
    deleting.value = true;

    try {
      await deleteHoliday(props.holiday.id);

      onDialogOK({
        action: "delete",
        id: props.holiday.id,
      });
    } catch {
      $q.notify({
        message: "Erro ao excluir feriado.",
        type: "negative",
      });
    } finally {
      deleting.value = false;
    }
  });
};

const save = async () => {
  const trimmedDescription = description.value.trim();

  if (!trimmedDescription) return;

  saving.value = true;

  try {
    const updatedHoliday = await updateHoliday(
      {
        description: trimmedDescription,
        holiday_date: props.holiday.holiday_date,
        type: type.value,
      },
      props.holiday.id,
    );

    onDialogOK({
      action: "update",
      holiday: {
        ...props.holiday,
        description: updatedHoliday.description,
        type: updatedHoliday.type,
      },
    });
  } catch {
    $q.notify({
      message: "Erro ao salvar feriado.",
      type: "negative",
    });
  } finally {
    saving.value = false;
  }
};
</script>

<style scoped>
.feriados-edit-dialog {
  width: 420px;
  max-width: 95vw;
}
</style>