<template>
    <MalioDrawer v-model="drawerOpen">
        <template #header>
            <h2 class="text-[32px] font-semibold text-primary-500">Export des heures</h2>
        </template>
        <form class="space-y-4" @submit.prevent="handleSubmit">
            <MalioDate
                v-model="selectedDate"
                label="Date"
                required
                :clearable="false"
                :reserve-message-space="false"
                group-class="w-full"
            />

            <MalioSelectCheckbox
                v-model="selectedSites"
                :options="siteOptions"
                label="Sites"
                required
                :reserve-message-space="false"
                groupClass="w-full"
                display-select-all
                display-tag
            />

            <div class="flex justify-center pt-2">
                <MalioButton
                    :label="isLoading ? 'Génération en cours...' : 'Exporter'"
                    button-class="w-[200px]"
                    :disabled="isLoading || !selectedDate || selectedSites.length === 0"
                    @click="handleSubmit"
                />
            </div>
        </form>
    </MalioDrawer>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { Site } from '~/services/dto/site'

const props = defineProps<{
    modelValue: boolean
    sites: Site[]
    initialDate: string
    isLoading?: boolean
}>()

const emit = defineEmits<{
    (event: 'update:modelValue', value: boolean): void
    (event: 'submit', payload: { date: string; siteIds: number[] }): void
}>()

const drawerOpen = computed({
    get: () => props.modelValue,
    set: (value: boolean) => emit('update:modelValue', value)
})

const selectedDate = ref(props.initialDate)
const selectedSites = ref<number[]>([])

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

const handleSubmit = () => {
    if (!selectedDate.value || selectedSites.value.length === 0) return
    emit('submit', { date: selectedDate.value, siteIds: [...selectedSites.value] })
}

watch(
    () => props.modelValue,
    (isOpen) => {
        if (isOpen) {
            selectedDate.value = props.initialDate
            selectedSites.value = []
        }
    }
)
</script>
