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

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

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

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

      <q-separator />

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

      <template v-else>
        <q-card-actions align="between">
          <q-btn
            v-if="canDelete"
            outline
            color="negative"
            label="EXCLUIR"
            no-caps
            :loading="deleting"
            @click="confirmDelete"
          />
          <div class="row q-gutter-sm">
            <q-btn outline color="primary" label="CANCELAR" no-caps @click="onDialogCancel" />
            <q-btn
              unelevated
              color="primary"
              label="SALVAR"
              no-caps
              :disable="!description.trim()"
              :loading="saving"
              @click="save"
            />
          </div>
        </q-card-actions>
      </template>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import { useDialogPluginComponent, useQuasar } from "quasar";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";
import { updateHoliday, deleteHoliday } from "src/api/holiday";
import { permissionStore } from "src/stores/permission";

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

const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();
const $q = useQuasar();
const permissions = permissionStore();
const canEdit = computed(() =>
  permissions.getAccess("franchisee_dashboard", "edit"),
);
const canDelete = computed(() =>
  permissions.getAccess("franchisee_dashboard", "delete"),
);

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

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

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

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

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

async function save() {
  const desc = description.value.trim();
  if (!desc) return;

  saving.value = true;
  try {
    const updated = await updateHoliday(
      { description: desc, holiday_date: props.holiday.holiday_date, type: type.value },
      props.holiday.id,
    );

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

function confirmDelete() {
  $q.dialog({
    title: "Excluir feriado",
    message: `Deseja excluir "${props.holiday.description}"?`,
    cancel: { label: "Cancelar", flat: true, color: "primary" },
    ok: { label: "Excluir", unelevated: true, color: "negative" },
  }).onOk(async () => {
    deleting.value = true;
    try {
      await deleteHoliday(props.holiday.id);
      onDialogOK({ action: "delete", id: props.holiday.id });
    } catch {
      $q.notify({ type: "negative", message: "Erro ao excluir feriado." });
    } finally {
      deleting.value = false;
    }
  });
}
</script>

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