<template>
  <q-dialog
    ref="dialogRef"
    @hide="onDialogHide"
  >
    <q-card
      class="card-border bg-surface text-text time-card relative-position"
    >
      <q-btn
        class="absolute-top-right close-button q-mt-sm q-mr-sm"
        color="grey-5"
        dense
        flat
        icon="mdi-close-circle-outline"
        round
        type="button"
        @click.stop="handleClose"
      />

      <q-card-section class="text-center q-pt-lg q-pb-xs">
        <div class="font16 fontbold text-text">
          {{ serviceType.label }}

          <span class="text-grey-6">
            {{ "(" + serviceType.hoursCount + "h)" }}
          </span>
        </div>

        <div class="font14 fontmedium text-grey-6 q-mt-xs">
          {{ $t("scheduling_page.time_selection.subtitle") }}
        </div>
      </q-card-section>

      <q-card-section class="q-pt-xs">
        <div class="row q-col-gutter-xs">
          <div
            v-for="slot in timeSlots"
            :key="slot.value"
            class="col-6"
          >
            <q-radio
              v-model="selectedSlot"
              class="font12 fontbold text-primary"
              color="primary"
              dense
              keep-color
              :label="slot.label"
              :val="slot.value"
            />
          </div>
        </div>
      </q-card-section>

      <template v-if="hasMealSection">
        <q-separator class="q-mx-md" />

        <q-card-section class="q-py-sm">
          <div class="font14 fontbold text-text q-mb-sm text-center">
            {{ $t("scheduling_page.time_selection.meal_section") }}
          </div>

          <div class="meal-options column items-start">
            <q-radio
              v-model="selectedMeal"
              class="font12 fontbold text-primary q-pb-sm"
              color="primary"
              dense
              keep-color
              val="offer"
              :label="$t('scheduling_page.time_selection.meal_offer')"
            />

            <q-radio
              v-model="selectedMeal"
              class="font12 fontbold text-primary q-pt-sm"
              color="primary"
              dense
              keep-color
              val="no_offer"
              :label="$t('scheduling_page.time_selection.meal_no_offer')"
            />
          </div>
        </q-card-section>
      </template>

      <q-card-actions class="q-px-md q-pb-xs q-pt-sm">
        <q-btn
          class="full-width"
          color="secondary"
          no-caps
          padding="4px 8px"
          rounded
          unelevated
          :disable="!selectedSlot"
          :label="$t('scheduling_page.time_selection.continue')"
          @click="handleContinue"
        />
      </q-card-actions>

      <div
        v-if="pauseNote"
        class="text-center font12 fontmedium text-primary q-pb-md"
      >
        {{ pauseNote }}
      </div>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { computed, ref } from "vue";
import { useDialogPluginComponent } from "quasar";
import { useI18n } from "vue-i18n";

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

const props = defineProps({
  partialBlocks: { default: () => [], required: false, type: Array },
  provider: { required: true, type: Object },
  selectedDate: { required: true, type: String },
  serviceType: { required: true, type: Object },
});

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

const selectedMeal = ref(null);
const selectedSlot = ref(null);

const slotConflicts = (slotStart, slotEnd, blocks) =>
  blocks.some((block) => {
    const blockEnd = parseInt(block.end_hour);
    const blockStart = parseInt(block.init_hour);

    return slotEnd >= blockStart && slotStart <= blockEnd;
  });

const hasMealSection = computed(() => props.serviceType.hoursCount >= 6);

const pauseNote = computed(() => {
  const map = {
    8: t("scheduling_page.time_selection.pause_note_8h"),
    6: t("scheduling_page.time_selection.pause_note_6h"),
    4: t("scheduling_page.time_selection.pause_note_4h"),
  };

  return map[props.serviceType.hoursCount] ?? null;
});

const timeSlots = computed(() => {
  const h = props.serviceType.hoursCount;

  const slots = [];

  const now = new Date();

  const today =
    `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;

  const isToday =
    props.selectedDate.replace(/\//g, "-") === today;

  const minimumHour = now.getHours() + 2;

  for (let start = 7; start + h <= 20; start++) {
    const end = start + h;

    // Se a data for hoje, bloqueia horários com menos de 2 horas de antecedência
    if (isToday && start < minimumHour) {
      continue;
    }

    if (slotConflicts(start, end, props.partialBlocks)) {
      continue;
    }

    slots.push({
      startHour: start,
      endHour: end,
      label: `${start}h às ${end}h`,
      value: `${start}-${end}`,
    });
  }

  return slots;
});

const handleClose = () => {
  dialogRef.value?.hide();
};

const handleContinue = () => {
  const slotObj = timeSlots.value.find(
    (slot) => slot.value === selectedSlot.value,
  );

  onDialogOK({
    date: props.selectedDate,
    meal: selectedMeal.value,
    serviceType: props.serviceType,
    slot: {
      endHour: slotObj.endHour,
      startHour: slotObj.startHour,
      value: selectedSlot.value,
    },
  });
};
</script>

<style scoped lang="scss">
.close-button {
  z-index: 2;
}

.time-card {
  width: min(88vw, 360px);
}

.meal-options {
  margin-inline: auto;
  width: fit-content;
}
</style>
