<template>
  <div class="py-4 flex flex-col gap-3 lg:py-6">
      <!-- Desktop: filters row -->
      <div class="hidden lg:flex lg:items-center lg:gap-4">
          <div v-if="sites.length > 0 && isAdmin" class="relative z-50 w-80">
              <MalioSelectCheckbox :reserve-message-space="false"
                  v-model="selectedSiteIds"
                  :options="siteOptions"
                  groupClass="w-80"
                  label="Sites"
                  display-select-all
              />
          </div>
          <div v-if="isAdmin" class="w-96">
              <MalioInputText :reserve-message-space="false"
                  v-model="employeeFilter"
                  label="Recherche d'un employé"
                  icon-name="mdi:magnify"
              />
          </div>
      </div>

      <!-- Mobile: search + filter button -->
      <div v-if="isAdmin" class="flex items-center gap-2 lg:hidden">
          <div class="flex-1 min-w-0">
              <MalioInputText :reserve-message-space="false"
                  v-model="employeeFilter"
                  label="Recherche d'un employé"
                  icon-name="mdi:magnify"
              />
          </div>
          <button
            type="button"
            class="flex h-10 w-10 shrink-0 items-center justify-center rounded-md border border-primary-500 bg-white text-primary-500"
            @click="filtersDrawerOpen = true"
          >
              <Icon name="mdi:filter-variant" size="22"/>
          </button>
      </div>

      <!-- Mobile filters drawer -->
      <MalioDrawer v-model="filtersDrawerOpen">
          <template #header>
              <h2 class="text-[32px] font-semibold text-primary-500">Filtres</h2>
          </template>
          <div class="space-y-6">
              <div v-if="sites.length > 0 && isAdmin">
                  <label class="text-md font-semibold text-neutral-700">Sites</label>
                  <div class="mt-2">
                      <MalioSelectCheckbox :reserve-message-space="false"
                          v-model="selectedSiteIds"
                          :options="siteOptions"
                          groupClass="w-80"
                          label="Sites"
                          display-select-all
                      />
                  </div>
              </div>
              <div v-if="isAdmin">
                  <label class="text-md font-semibold text-neutral-700">Vue</label>
                  <div class="mt-2 inline-flex h-10 w-full overflow-hidden rounded-md border border-primary-500 bg-white">
                      <button
                        type="button"
                        class="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 text-sm font-semibold"
                        :class="viewModeButtonClass('day')"
                        @click="viewMode = 'day'; filtersDrawerOpen = false"
                      >
                          <Icon name="mdi:calendar-clock" />
                          Jour
                      </button>
                      <button
                        type="button"
                        class="flex-1 inline-flex items-center justify-center gap-2 border-l border-primary-500 px-4 py-2 text-sm font-semibold"
                        :class="viewModeButtonClass('week')"
                        @click="viewMode = 'week'; filtersDrawerOpen = false"
                      >
                          <Icon name="mdi:calendar-week" />
                          Semaine
                      </button>
                  </div>
              </div>
          </div>
      </MalioDrawer>

    <!-- Date navigation -->
    <div class="flex flex-col gap-3 lg:flex-row lg:justify-between lg:items-center lg:gap-4">
      <div class="flex flex-col gap-3 lg:flex-row lg:flex-wrap lg:items-center lg:gap-4">
      <div
        v-if="viewMode === 'day'"
        class="inline-flex h-10 w-full overflow-hidden rounded-md border border-primary-500 bg-white lg:w-[320px]"
      >
        <button
          type="button"
          class="flex-1 px-4 py-2 text-sm font-semibold active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40"
          :class="shortcutButtonClass('yesterday')"
          @click="emit('set-yesterday')"
        >
          Hier
        </button>
        <button
          type="button"
          class="flex-1 border-x border-primary-500 px-4 py-2 text-sm font-semibold active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40"
          :class="shortcutButtonClass('today')"
          @click="emit('set-today')"
        >
          Aujourd'hui
        </button>
        <button
          type="button"
          class="flex-1 px-4 py-2 text-sm font-semibold active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40"
          :class="shortcutButtonClass('tomorrow')"
          @click="emit('set-tomorrow')"
        >
          Demain
        </button>
      </div>

      <div
        v-else
        class="inline-flex h-10 w-full overflow-hidden rounded-md border border-primary-500 bg-white lg:w-[320px]"
      >
        <button
          type="button"
          class="flex-1 px-4 py-2 text-sm font-semibold active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40"
          :class="weekShortcutButtonClass('previousWeek')"
          @click="emit('set-previous-week')"
        >
          {{ getWeekShortcutLabel('previousWeek') }}
        </button>
        <button
          type="button"
          class="flex-1 border-x border-primary-500 px-4 py-2 text-sm font-semibold active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40"
          :class="weekShortcutButtonClass('thisWeek')"
          @click="emit('set-this-week')"
        >
          {{ getWeekShortcutLabel('thisWeek') }}
        </button>
        <button
          type="button"
          class="flex-1 px-4 py-2 text-sm font-semibold active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40"
          :class="weekShortcutButtonClass('nextWeek')"
          @click="emit('set-next-week')"
        >
          {{ getWeekShortcutLabel('nextWeek') }}
        </button>
      </div>

      <!-- Vue Jour (opt-in) : calendrier Malio avec jours validés en vert (markedDates). -->
      <MalioDate
        v-if="viewMode === 'day' && showValidationCalendar"
        :model-value="selectedDate"
        :clearable="false"
        :reserve-message-space="false"
        :marked-dates="markedDates"
        group-class="w-full lg:w-96"
        label="Date"
        @update:model-value="onDatePicked"
        @month-change="(payload) => emit('month-change', payload)"
      />
      <!-- Vue Semaine : sélecteur de semaine Malio. -->
      <MalioDateWeek
        v-else-if="viewMode === 'week'"
        :model-value="pickerValue"
        :clearable="false"
        :reserve-message-space="false"
        group-class="w-full lg:w-96"
        label="Semaine"
        @update:model-value="onWeekPicked"
      />
      <PeriodStepperPicker
        v-else
        width-class="w-full lg:w-[320px]"
        :label="formattedSelectedDate"
        picker-type="date"
        :picker-value="pickerValue"
        prev-aria-label="Période précédente"
        next-aria-label="Période suivante"
        @prev="emit('shift-date', -1)"
        @next="emit('shift-date', 1)"
        @pick="onPickerValue"
      />
      </div>

      <!-- Desktop: view mode toggle -->
      <div v-if="isAdmin" class="hidden lg:inline-flex h-10 overflow-hidden rounded-md border border-primary-500 bg-white">
        <button
          type="button"
          class="inline-flex items-center gap-2 px-4 py-2 text-sm font-semibold active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40"
          :class="viewModeButtonClass('day')"
          @click="viewMode = 'day'"
        >
          <Icon name="mdi:calendar-clock" />
          Jour
        </button>
        <button
          type="button"
          class="inline-flex items-center gap-2 border-l border-primary-500 px-4 py-2 text-sm font-semibold active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40"
          :class="viewModeButtonClass('week')"
          @click="viewMode = 'week'"
        >
          <Icon name="mdi:calendar-week" />
          Semaine
        </button>
      </div>
    </div>

    <div
      v-if="isAdmin && viewMode === 'week' && absenceTypes.length > 0"
      class="hidden lg:flex flex-wrap items-center gap-6"
    >
      <p class="font-bold">Légende :</p>
      <div v-for="type in absenceTypes" :key="type.id" class="flex items-center gap-2">
        <div :style="{ backgroundColor: type.color }" class="h-4 w-4 rounded"></div>
        <p>{{ type.label }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Site } from '~/services/dto/site'
import type { AbsenceType } from '~/services/dto/absence-type'
import PeriodStepperPicker from '~/components/PeriodStepperPicker.vue'
import { weekInputValueToYmd, ymdToWeekInputValue } from '~/utils/date'

const selectedDate = defineModel<string>('selectedDate', { required: true })
const viewMode = defineModel<'day' | 'week'>('viewMode', { required: true })
const selectedSiteIds = defineModel<number[]>('selectedSiteIds', { required: true })
const employeeFilter = defineModel<string>('employeeFilter', { required: true })

const props = defineProps<{
  isAdmin: boolean
  sites: Site[]
  absenceTypes: AbsenceType[]
  formattedSelectedDate: string
  // Calendrier des jours validés (vert) : opt-in, réservé à l'écran Heures.
  // L'écran Heures Conducteurs ne le passe pas → garde le PeriodStepperPicker.
  showValidationCalendar?: boolean
  markedDates?: Record<string, 'success' | 'danger'>
  shortcutButtonClass: (target: 'yesterday' | 'today' | 'tomorrow') => string
  weekShortcutButtonClass: (target: 'previousWeek' | 'thisWeek' | 'nextWeek') => string
  getWeekShortcutLabel: (target: 'previousWeek' | 'thisWeek' | 'nextWeek') => string
}>()

const siteOptions = computed(() => props.sites.map((site) => ({ label: site.name, value: site.id })))

const emit = defineEmits<{
  (e: 'set-yesterday'): void
  (e: 'set-today'): void
  (e: 'set-tomorrow'): void
  (e: 'set-previous-week'): void
  (e: 'set-this-week'): void
  (e: 'set-next-week'): void
  (e: 'shift-date', value: number): void
  (e: 'month-change', value: { month: number; year: number }): void
}>()

const filtersDrawerOpen = ref(false)

const pickerValue = computed(() => {
  if (viewMode.value === 'week') return ymdToWeekInputValue(selectedDate.value)
  return selectedDate.value
})

const viewModeButtonClass = (mode: 'day' | 'week') => {
  if (viewMode.value === mode) {
    return 'bg-primary-500 text-white'
  }

  return 'bg-white text-primary-500 hover:bg-tertiary-500'
}

const onPickerValue = (value: string) => {
  if (!value) return

  if (viewMode.value === 'week') {
    const ymd = weekInputValueToYmd(value)
    if (!ymd) return
    selectedDate.value = ymd
    return
  }

  selectedDate.value = value
}

// Sélection d'un jour dans le calendrier MalioDate (vue Jour). `clearable=false`
// → pas de null en pratique, mais on garde la garde par sécurité.
const onDatePicked = (value: string | null) => {
  if (!value) return
  selectedDate.value = value
}

// Sélection d'une semaine dans MalioDateWeek (vue Semaine) : v-model au format ISO
// week (YYYY-Www) → on repositionne selectedDate sur le lundi de cette semaine.
const onWeekPicked = (value: string | null) => {
  if (!value) return
  const ymd = weekInputValueToYmd(value)
  if (!ymd) return
  selectedDate.value = ymd
}
</script>
