<template>
    <MalioDrawer v-model="isOpen" :title="$t('timeEntries.exportTitle')" drawer-class="max-w-lg">
        <div class="flex flex-col gap-6 p-4">
            <!-- Period presets -->
            <div>
                <p class="mb-2 text-sm font-semibold text-neutral-700">Période</p>
                <div class="flex flex-col gap-2">
                    <MalioRadioButton
                        v-model="periodMode"
                        name="exportPeriod"
                        value="currentMonth"
                        :label="$t('timeEntries.exportCurrentMonth')"
                    />
                    <MalioRadioButton
                        v-model="periodMode"
                        name="exportPeriod"
                        value="lastMonth"
                        :label="$t('timeEntries.exportLastMonth')"
                    />
                    <MalioRadioButton
                        v-model="periodMode"
                        name="exportPeriod"
                        value="custom"
                        :label="$t('timeEntries.exportCustomPeriod')"
                    />
                </div>
                <div v-if="periodMode === 'custom'" class="mt-3 flex items-center gap-3">
                    <div class="flex-1">
                        <label class="mb-1 block text-xs text-neutral-500">{{ $t('timeEntries.exportFrom') }}</label>
                        <input
                            v-model="customFrom"
                            type="date"
                            class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm"
                        />
                    </div>
                    <div class="flex-1">
                        <label class="mb-1 block text-xs text-neutral-500">{{ $t('timeEntries.exportTo') }}</label>
                        <input
                            v-model="customTo"
                            type="date"
                            class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm"
                        />
                    </div>
                </div>
            </div>

            <!-- User filter (admin only) -->
            <div v-if="isAdmin" class="[&>div]:!mt-0">
                <MalioSelectCheckbox
                    v-model="selectedUserIds"
                    :options="userOptions"
                    :label="$t('timeEntries.exportUsers')"
                    :display-tag="true"
                    :display-select-all="true"
                    min-width="!w-full"
                />
            </div>

            <!-- Client filter -->
            <div class="[&>div]:!mt-0">
                <MalioSelect
                    v-model="selectedClientId"
                    :options="clientOptions"
                    :label="$t('timeEntries.exportClient')"
                    :empty-option-label="$t('timeEntries.exportAllClients')"
                    min-width="!w-full"
                />
            </div>

            <!-- Project filter -->
            <div class="[&>div]:!mt-0">
                <MalioSelectCheckbox
                    v-model="selectedProjectIds"
                    :options="filteredProjectOptions"
                    :label="$t('timeEntries.exportProjects')"
                    :display-tag="true"
                    :display-select-all="true"
                    min-width="!w-full"
                />
            </div>

            <!-- Tag filter -->
            <div class="[&>div]:!mt-0">
                <MalioSelectCheckbox
                    v-model="selectedTagIds"
                    :options="tagOptions"
                    :label="$t('timeEntries.exportTags')"
                    :display-tag="true"
                    :display-select-all="true"
                    min-width="!w-full"
                />
            </div>

            <!-- Export button -->
            <MalioButton
                :label="$t('timeEntries.export')"
                icon-name="mdi:download"
                icon-position="left"
                button-class="w-full"
                @click="doExport"
            />
        </div>
    </MalioDrawer>
</template>

<script setup lang="ts">
import type { UserData } from '~/services/dto/user-data'
import type { Project } from '~/services/dto/project'
import type { TaskTag } from '~/services/dto/task-tag'
import type { Client } from '~/services/dto/client'

const props = defineProps<{
    users: UserData[]
    projects: Project[]
    tags: TaskTag[]
    clients: Client[]
}>()

const isOpen = defineModel<boolean>({ default: false })
const emit = defineEmits<{
    (e: 'export', params: {
        after: string
        before: string
        users?: number[]
        projects?: number[]
        client?: number
        tags?: number[]
    }): void
}>()

const authStore = useAuthStore()
const isAdmin = computed(() => authStore.user?.roles?.includes('ROLE_ADMIN') ?? false)

const periodMode = ref<'currentMonth' | 'lastMonth' | 'custom'>('currentMonth')
const customFrom = ref('')
const customTo = ref('')
const selectedUserIds = ref<number[]>([])
const selectedClientId = ref<number | null>(null)
const selectedProjectIds = ref<number[]>([])
const selectedTagIds = ref<number[]>([])

const userOptions = computed(() =>
    props.users.map(u => ({ label: u.username, value: u.id }))
)

const clientOptions = computed(() =>
    props.clients.map(c => ({ label: c.name, value: c.id }))
)

const filteredProjectOptions = computed(() => {
    let list = props.projects
    if (selectedClientId.value) {
        list = list.filter(p => p.client?.id === selectedClientId.value)
    }
    return list.map(p => ({ label: p.name, value: p.id }))
})

const tagOptions = computed(() =>
    props.tags.map(t => ({ label: t.label, value: t.id }))
)

// Reset project selection when client changes
watch(selectedClientId, () => {
    selectedProjectIds.value = []
})

function getDateRange(): { after: string; before: string } {
    const now = new Date()
    if (periodMode.value === 'currentMonth') {
        const first = new Date(now.getFullYear(), now.getMonth(), 1)
        const last = new Date(now.getFullYear(), now.getMonth() + 1, 1)
        return {
            after: first.toISOString().slice(0, 10),
            before: last.toISOString().slice(0, 10),
        }
    }
    if (periodMode.value === 'lastMonth') {
        const first = new Date(now.getFullYear(), now.getMonth() - 1, 1)
        const last = new Date(now.getFullYear(), now.getMonth(), 1)
        return {
            after: first.toISOString().slice(0, 10),
            before: last.toISOString().slice(0, 10),
        }
    }
    return {
        after: customFrom.value,
        before: customTo.value,
    }
}

function doExport() {
    const { after, before } = getDateRange()
    if (!after || !before) return

    emit('export', {
        after,
        before,
        users: selectedUserIds.value.length ? selectedUserIds.value : undefined,
        projects: selectedProjectIds.value.length ? selectedProjectIds.value : undefined,
        client: selectedClientId.value ?? undefined,
        tags: selectedTagIds.value.length ? selectedTagIds.value : undefined,
    })
    isOpen.value = false
}
</script>
