<script setup lang="ts">
import { format } from 'date-fns'
// Simple, API-ready Dienstplan view without fixed shift types.

type Employee = {
    id: string
    name: string
}

type ShiftAssignment = {
    employee_id: string
    name: string
}

type Shift = {
    id: string
    date: string // YYYY-MM-DD
    start_time: string // HH:mm
    end_time: string // HH:mm
    label?: string
    notes?: string
    assignments: ShiftAssignment[]
}

type Branch = {
    id: string
    name: string
}

type AvailabilityWindow = {
    start_time: string
    end_time: string
}

type ScheduleResult = {
    assigned: { shift_id: string; employee_id: string }[]
    unfilled: { shift_id: string; missing: number }[]
    conflicts: { shift_id: string; employee_id: string; reason: string }[]
}

const employees: Employee[] = [
    { id: 'emp_anna', name: 'Anna Keller' },
    { id: 'emp_mehmet', name: 'Mehmet Aydin' },
    { id: 'emp_lisa', name: 'Lisa Schmidt' },
    { id: 'emp_anna2', name: 'Anna Keller2' },
    { id: 'emp_mehmet2', name: 'Mehmet Aydin2' },
    { id: 'emp_lisa2', name: 'Lisa Schmidt2' },
    { id: 'emp_anna3', name: 'Anna Keller3' },
    { id: 'emp_mehmet3', name: 'Mehmet Aydin3' },
    { id: 'emp_lisa3', name: 'Lisa Schmidt3' }
]

const mockAvailabilityRules: Record<string, Record<number, AvailabilityWindow[]>> = {
    emp_anna: {
        0: [{ start_time: '08:00', end_time: '16:00' }],
        1: [{ start_time: '08:00', end_time: '16:00' }],
        2: [{ start_time: '10:00', end_time: '18:00' }],
        4: [{ start_time: '08:00', end_time: '14:00' }]
    },
    emp_mehmet: {
        0: [{ start_time: '12:00', end_time: '20:00' }],
        2: [{ start_time: '08:00', end_time: '12:00' }],
        3: [{ start_time: '08:00', end_time: '16:00' }]
    },
    emp_lisa: {
        1: [{ start_time: '06:00', end_time: '12:00' }],
        4: [{ start_time: '12:00', end_time: '20:00' }]
    }
}

const selectedBranchId = ref('branch_berlin')
const today = new Date()
const weekStart = ref(getWeekStart(today))
const selectedMobileDayIndex = ref(0)

const shifts = ref<Shift[]>([])

const weekDays = computed(() => {
    const days: { date: Date; key: string; label: string }[] = []
    for (let i = 0; i < 7; i += 1) {
        const date = addDays(weekStart.value, i)
        days.push({
            date,
            key: toISODate(date),
            label: formatDayHeader(date)
        })
    }
    return days
})

const weekLabel = computed(() => {
    const start = weekStart.value
    const end = addDays(start, 6)
    return formatWeekRange(start, end)
})

const shiftsByDay = computed(() => {
    const map = new Map<string, Shift[]>()
    for (const day of weekDays.value) {
        map.set(day.key, [])
    }
    for (const shift of shifts.value) {
        const list = map.get(shift.date)
        if (list) {
            list.push(shift)
        }
    }
    for (const list of map.values()) {
        list.sort((a, b) => timeToMinutes(a.start_time) - timeToMinutes(b.start_time))
    }
    return map
})

const conflictsByShiftId = computed(() => {
    const map = new Map<string, Set<string>>()
    const byDate = new Map<string, Shift[]>()

    for (const shift of shifts.value) {
        const list = byDate.get(shift.date) ?? []
        list.push(shift)
        byDate.set(shift.date, list)
    }

    for (const dayShifts of byDate.values()) {
        const employeeAssignments = new Map<string, Shift[]>()
        for (const shift of dayShifts) {
            for (const assignment of shift.assignments) {
                const list = employeeAssignments.get(assignment.employee_id) ?? []
                list.push(shift)
                employeeAssignments.set(assignment.employee_id, list)
            }
        }

        for (const [employeeId, assignedShifts] of employeeAssignments.entries()) {
            for (let i = 0; i < assignedShifts.length; i += 1) {
                for (let j = i + 1; j < assignedShifts.length; j += 1) {
                    if (rangesOverlap(assignedShifts[i], assignedShifts[j])) {
                        const firstSet = map.get(assignedShifts[i].id) ?? new Set<string>()
                        const secondSet = map.get(assignedShifts[j].id) ?? new Set<string>()
                        firstSet.add(employeeId)
                        secondSet.add(employeeId)
                        map.set(assignedShifts[i].id, firstSet)
                        map.set(assignedShifts[j].id, secondSet)
                    }
                }
            }
        }
    }

    return map
})

const isShiftConflicted = (shift: Shift) => {
    return Boolean(conflictsByShiftId.value.get(shift.id)?.size)
}

const isEmployeeConflicted = (shift: Shift, employeeId: string) => {
    return conflictsByShiftId.value.get(shift.id)?.has(employeeId) ?? false
}

const goToPreviousWeek = () => {
    weekStart.value = addDays(weekStart.value, -7)
    selectedMobileDayIndex.value = 0
    loadShifts()
}

const goToCurrentWeek = () => {
    weekStart.value = getWeekStart(new Date())
    selectedMobileDayIndex.value = 0
    loadShifts()
}

const goToNextWeek = () => {
    weekStart.value = addDays(weekStart.value, 7)
    selectedMobileDayIndex.value = 0
    loadShifts()
}

const isAutoScheduleModalOpen = ref(false)
const autoScheduleForm = reactive({
    from: toISODate(weekStart.value),
    to: toISODate(addDays(weekStart.value, 6)),
    options: {
        respect_availability: true,
        avoid_overlaps: true,
        fair_distribution: true
    }
})
const autoScheduleResult = ref<ScheduleResult | null>(null)
const isAutoScheduleLoading = ref(false)
const mockScheduleResult = (currentShifts: Shift[]): ScheduleResult => {
    const assigned = currentShifts
        .filter((shift) => shift.assignments.length === 0)
        .map((shift) => ({ shift_id: shift.id, employee_id: employees[0]?.id ?? 'emp_anna' }))

    const unfilled = currentShifts
        .filter((shift, index) => index % 5 === 0)
        .map((shift) => ({ shift_id: shift.id, missing: 1 }))

    const conflicts = currentShifts
        .filter((shift, index) => index % 7 === 0)
        .map((shift) => ({ shift_id: shift.id, employee_id: employees[1]?.id ?? 'emp_mehmet', reason: 'OVERLAP' }))

    return { assigned, unfilled, conflicts }
}

const openAutoScheduleModal = () => {
    autoScheduleForm.from = toISODate(weekStart.value)
    autoScheduleForm.to = toISODate(addDays(weekStart.value, 6))
    autoScheduleResult.value = null
    isAutoScheduleModalOpen.value = true
}

const runAutoSchedule = async (apply: boolean) => {
    isAutoScheduleLoading.value = true
    try {
        const result = mockScheduleResult(shifts.value)
        autoScheduleResult.value = result
        if (apply) {
            for (const item of result.assigned) {
                const shift = shifts.value.find((entry) => entry.id === item.shift_id)
                if (!shift) {
                    continue
                }
                if (shift.assignments.some((assignment) => assignment.employee_id === item.employee_id)) {
                    continue
                }
                const employee = employees.find((entry) => entry.id === item.employee_id)
                shift.assignments.push({
                    employee_id: item.employee_id,
                    name: employee?.name ?? 'Mitarbeiter'
                })
            }
        }
    } finally {
        isAutoScheduleLoading.value = false
    }
}

const unfilledShiftIds = computed(() => new Set(autoScheduleResult.value?.unfilled.map((item) => item.shift_id) ?? []))
const conflictShiftIds = computed(() => new Set(autoScheduleResult.value?.conflicts.map((item) => item.shift_id) ?? []))

watch(selectedBranchId, () => {
    loadShifts()
})

const loadShifts = () => {
    // TODO: Replace with API call when backend is ready.
    // Example: GET /shifts/branches/{branch_id}?from=YYYY-MM-DD&to=YYYY-MM-DD
    shifts.value = buildMockShifts(weekStart.value)
}

loadShifts()

const isShiftModalOpen = ref(false)
const shiftForm = reactive({
    date: toISODate(today),
    start_time: '08:00',
    end_time: '16:00',
    label: '',
    notes: ''
})

const openShiftModal = (date?: string) => {
    shiftForm.date = date ?? toISODate(weekStart.value)
    shiftForm.start_time = '08:00'
    shiftForm.end_time = '16:00'
    shiftForm.label = ''
    shiftForm.notes = ''
    isShiftModalOpen.value = true
}

const saveShift = () => {
    const newShift: Shift = {
        id: `shift_${Math.random().toString(36).slice(2, 9)}`,
        date: shiftForm.date,
        start_time: shiftForm.start_time,
        end_time: shiftForm.end_time,
        label: shiftForm.label || undefined,
        notes: shiftForm.notes || undefined,
        assignments: []
    }

    shifts.value.push(newShift)
    isShiftModalOpen.value = false
}

const isAssignModalOpen = ref(false)
const assignContext = ref<Shift | null>(null)
const employeeSearch = ref('')
const selectedEmployeeIds = ref<string[]>([])

const openAssignModal = (shift: Shift) => {
    assignContext.value = shift
    selectedEmployeeIds.value = shift.assignments.map((assignment) => assignment.employee_id)
    employeeSearch.value = ''
    isAssignModalOpen.value = true
}

const closeAssignModal = () => {
    isAssignModalOpen.value = false
    assignContext.value = null
    selectedEmployeeIds.value = []
}

const filteredEmployees = computed(() => {
    const query = employeeSearch.value.trim().toLowerCase()
    if (!query) {
        return employees
    }
    return employees.filter((employee) => employee.name.toLowerCase().includes(query))
})

const weekdayIndex = (value: string) => {
    const date = new Date(`${value}T00:00:00`)
    const day = date.getDay()
    return (day + 6) % 7
}

const availabilityStatus = (employeeId: string, shift: Shift | null) => {
    if (!shift) {
        return { status: 'unknown', partial: [] as AvailabilityWindow[] }
    }
    const rules = mockAvailabilityRules[employeeId]
    if (!rules) {
        return { status: 'unknown', partial: [] as AvailabilityWindow[] }
    }
    const dayRules = rules[weekdayIndex(shift.date)]
    if (!dayRules || dayRules.length === 0) {
        return { status: 'unknown', partial: [] as AvailabilityWindow[] }
    }

    const shiftStart = timeToMinutes(shift.start_time)
    let shiftEnd = timeToMinutes(shift.end_time)
    if (shiftEnd <= shiftStart) {
        shiftEnd += 24 * 60
    }

    const partial: AvailabilityWindow[] = []
    for (const window of dayRules) {
        let windowStart = timeToMinutes(window.start_time)
        let windowEnd = timeToMinutes(window.end_time)
        if (windowEnd <= windowStart) {
            windowEnd += 24 * 60
        }
        if (windowStart <= shiftStart && windowEnd >= shiftEnd) {
            return { status: 'available', partial: [] }
        }
        if (windowStart < shiftEnd && shiftStart < windowEnd) {
            const overlapStart = Math.max(windowStart, shiftStart)
            const overlapEnd = Math.min(windowEnd, shiftEnd)
            const formatMinutes = (value: number) => {
                const normalized = value % (24 * 60)
                const hours = Math.floor(normalized / 60)
                const minutes = normalized % 60
                return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
            }
            partial.push({
                start_time: formatMinutes(overlapStart),
                end_time: formatMinutes(overlapEnd)
            })
        }
    }

    return { status: partial.length ? 'partial' : 'unavailable', partial }
}

const groupedEmployees = computed(() => {
    const groups = {
        available: [] as Employee[],
        partial: [] as (Employee & { partial: AvailabilityWindow[] })[],
        unavailable: [] as Employee[],
        unknown: [] as Employee[]
    }
    for (const employee of filteredEmployees.value) {
        const result = availabilityStatus(employee.id, assignContext.value)
        if (result.status === 'partial') {
            groups.partial.push({ ...employee, partial: result.partial })
        } else {
            groups[result.status].push(employee)
        }
    }
    return groups
})

const saveAssignments = () => {
    if (!assignContext.value) {
        return
    }

    const updatedAssignments = selectedEmployeeIds.value
        .map((id) => {
            const employee = employees.find((item) => item.id === id)
            return employee ? { employee_id: employee.id, name: employee.name } : null
        })
        .filter(Boolean) as ShiftAssignment[]

    assignContext.value.assignments = updatedAssignments

    // TODO: Replace with API call when backend is ready.
    // Example: POST /shifts/{shift_id}/assignments with X-Org-Id header.

    closeAssignModal()
}

const removeAssignment = (shift: Shift, employeeId: string) => {
    shift.assignments = shift.assignments.filter((assignment) => assignment.employee_id !== employeeId)
    // TODO: Replace with API call when backend is ready.
    // Example: POST /shifts/{shift_id}/assignments with updated list or a DELETE endpoint.
}

const mobileDay = computed(() => weekDays.value[selectedMobileDayIndex.value])

const goToPreviousDay = () => {
    if (selectedMobileDayIndex.value > 0) {
        selectedMobileDayIndex.value -= 1
    }
}

const goToNextDay = () => {
    if (selectedMobileDayIndex.value < 6) {
        selectedMobileDayIndex.value += 1
    }
}

function buildMockShifts(start: Date): Shift[] {
    const monday = toISODate(start)
    const tuesday = toISODate(addDays(start, 1))
    const wednesday = toISODate(addDays(start, 2))

    return [
        {
            id: 'shift_early',
            date: monday,
            start_time: '04:00',
            end_time: '12:00',
            label: 'Früh',
            assignments: [{ employee_id: 'emp_anna', name: 'Anna Keller' }]
        },
        {
            id: 'shift_late',
            date: monday,
            start_time: '12:00',
            end_time: '20:00',
            label: 'Spät',
            assignments: [{ employee_id: 'emp_lisa', name: 'Lisa Schmidt' }]
        },
        {
            id: 'shift_sale',
            date: wednesday,
            start_time: '12:00',
            end_time: '18:00',
            label: 'Verkauf',
            assignments: [{ employee_id: 'emp_mehmet', name: 'Mehmet Aydin' }]
        },
        {
            id: 'shift_mid',
            date: wednesday,
            start_time: '12:00',
            end_time: '20:00',
            label: 'Spät',
            assignments: [{ employee_id: 'emp_mehmet', name: 'Mehmet Aydin' }]
        },
        {
            id: 'shift_short',
            date: "2026-01-29",
            start_time: '09:00',
            end_time: '15:00',
            label: 'Service',
            assignments: []
        }
    ]
}

function addDays(date: Date, days: number) {
    const result = new Date(date)
    result.setDate(result.getDate() + days)
    return result
}

function getWeekStart(date: Date) {
    const copy = new Date(date)
    const day = copy.getDay()
    const diff = (day === 0 ? -6 : 1) - day
    copy.setDate(copy.getDate() + diff)
    copy.setHours(0, 0, 0, 0)
    return copy
}

function toISODate(date: Date) {
    return format(date, 'yyyy-MM-dd')
}

function formatWeekRange(start: Date, end: Date) {
    const startLabel = start.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' })
    const endLabel = end.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' })
    return `${startLabel} – ${endLabel}`
}

function formatDayHeader(date: Date) {
    return date.toLocaleDateString('de-DE', {
        weekday: 'long',
        day: '2-digit',
        month: '2-digit'
    })
}

function timeToMinutes(value: string) {
    const [hours, minutes] = value.split(':').map((part) => Number(part))
    return hours * 60 + minutes
}

function rangesOverlap(a: Shift, b: Shift) {
    const startA = timeToMinutes(a.start_time)
    let endA = timeToMinutes(a.end_time)
    const startB = timeToMinutes(b.start_time)
    let endB = timeToMinutes(b.end_time)

    if (endA <= startA) {
        endA += 24 * 60
    }
    if (endB <= startB) {
        endB += 24 * 60
    }

    return startA < endB && startB < endA
}
</script>

<template>
    <UDashboardPanel id="dienstplan">
        <template #header>
            <UDashboardNavbar title="Dienstplan">
                <template #leading>
                    <UDashboardSidebarCollapse />
                </template>
            </UDashboardNavbar>
            <div class="border-b border-default px-4 py-5 sm:px-6">
                <!-- WEB VIEW-->
                <div class="hidden lg:block">
                    <div class="rounded-2xl border border-default bg-elevated p-4 shadow-sm">
                        <div class="flex flex-wrap items-center justify-between gap-4">
                            <div>
                                <div class="text-sm font-semibold text-muted">Woche</div>
                                <div class="text-2xl font-semibold text-default">{{ weekLabel }}</div>
                            </div>
                            <div class="flex flex-wrap items-center gap-3">
                                <UButton size="lg" color="neutral" variant="outline" label="Vorige Woche"
                                    @click="goToPreviousWeek" />
                                <UButton size="lg" color="neutral" variant="outline" label="Heute"
                                    @click="goToCurrentWeek" />
                                <UButton size="lg" color="neutral" variant="outline" label="Nächste Woche"
                                    @click="goToNextWeek" />
                                <UButton size="lg" color="neutral" variant="outline" label="Plan automatisch erstellen"
                                    @click="openAutoScheduleModal" />
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Mobile VIEW-->
                <div class="space-y-4 lg:hidden">
                    <div class="rounded-2xl border border-default bg-elevated p-4">
                        <div class="flex items-center justify-between gap-3">
                            <UButton size="lg" color="neutral" variant="outline" label="Voriger Tag"
                                @click="goToPreviousDay" />
                            <div class="text-lg font-semibold text-default text-center">{{ mobileDay?.label }}</div>
                            <UButton size="lg" color="neutral" variant="outline" label="Nächster Tag"
                                @click="goToNextDay" />
                        </div>
                    </div>
                </div>
            </div>
        </template>
        <template #body>
            <!-- WEB VIEW-->
            <div class="space-y-6 px-4 py-1 sm:px-6 lg:block">
                <div class="hidden lg:block">
                    <div class="max-h-[82vh] overflow-x-auto overflow-y-auto rounded-2xl p-4">
                        <!-- border border-default bg-elevated-->
                        <div class="min-w-490">
                            <div class="grid grid-cols-7 gap-4">
                                <div v-for="day in weekDays" :key="day.key"
                                    class="min-w-[270px] rounded-2xl border border-default bg-elevated p-4">
                                    <div class="border-b border-default pb-3 text-lg font-semibold text-default">
                                        {{ day.label }}
                                    </div>
                                    <div class="mt-3">
                                        <UButton size="lg" color="neutral" variant="outline" label="Schicht hinzufügen"
                                            class="w-full" @click="openShiftModal(day.key)" />
                                    </div>
                                    <div class="mt-4 space-y-4">
                                        <div v-for="shift in shiftsByDay.get(day.key) ?? []" :key="shift.id" :class="[
                                            'rounded-xl border border-zinc-700/70 bg-zinc-900/70 p-4',
                                            {
                                                'border-yellow-400': unfilledShiftIds.has(shift.id),
                                                'border-red-500': conflictShiftIds.has(shift.id)
                                            }
                                        ]">
                                            <div class="text-xl font-semibold text-default">
                                                {{ shift.start_time }} – {{ shift.end_time }}
                                            </div>
                                            <div v-if="shift.label" class="text-base font-semibold text-muted">
                                                {{ shift.label }}
                                            </div>

                                            <div class="mt-3 flex flex-wrap gap-2">
                                                <span v-for="assignment in shift.assignments"
                                                    :key="assignment.employee_id"
                                                    class="rounded-full border border-zinc-700/70 bg-muted/20 px-3 py-1 text-sm font-medium text-default">
                                                    {{ assignment.name }}
                                                    <span v-if="isEmployeeConflicted(shift, assignment.employee_id)"
                                                        class="ml-1 text-red-500">⚠</span>
                                                </span>
                                                <span v-if="shift.assignments.length === 0"
                                                    class="text-sm text-muted">Noch
                                                    niemand
                                                    zugewiesen.</span>
                                            </div>

                                            <button type="button"
                                                class="mt-3 text-sm font-semibold text-primary-400 underline"
                                                @click="openAssignModal(shift)">
                                                + Mitarbeiter hinzufügen
                                            </button>

                                            <div v-if="isShiftConflicted(shift)"
                                                class="mt-2 text-sm font-semibold text-red-500">
                                                ⚠ Überschneidung im Dienstplan
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- MOBILE VIEW-->
            <div class="rounded-2xl border border-default bg-elevated p-4 lg:hidden">
                <UButton size="lg" color="primary" label="Schicht hinzufügen" class="w-full"
                    @click="openShiftModal(mobileDay?.key)" />
                <UButton size="lg" color="neutral" variant="outline" label="Plan automatisch erstellen"
                    class="mt-3 w-full" @click="openAutoScheduleModal" />
                <div class="mt-4 space-y-4">
                    <div v-for="shift in shiftsByDay.get(mobileDay?.key ?? '') ?? []" :key="shift.id" :class="[
                        'rounded-xl border border-zinc-700/70 bg-zinc-900/70 p-4',
                        {
                            'border-yellow-400': unfilledShiftIds.has(shift.id),
                            'border-red-500': conflictShiftIds.has(shift.id)
                        }
                    ]">
                        <div class="text-xl font-semibold text-default">
                            {{ shift.start_time }} – {{ shift.end_time }}
                        </div>
                        <div v-if="shift.label" class="text-base font-semibold text-muted">
                            {{ shift.label }}
                        </div>

                        <div class="mt-3 flex flex-wrap gap-2">
                            <span v-for="assignment in shift.assignments" :key="assignment.employee_id"
                                class="rounded-full border border-zinc-700/70 bg-muted/20 px-3 py-1 text-sm font-medium text-default">
                                {{ assignment.name }}
                                <span v-if="isEmployeeConflicted(shift, assignment.employee_id)"
                                    class="ml-1 text-red-500">⚠</span>
                            </span>
                            <span v-if="shift.assignments.length === 0" class="text-sm text-muted">Noch niemand
                                zugewiesen.</span>
                        </div>

                        <button type="button" class="mt-3 text-sm font-semibold text-primary-400 underline"
                            @click="openAssignModal(shift)">
                            + Mitarbeiter hinzufügen
                        </button>

                        <div v-if="isShiftConflicted(shift)" class="mt-2 text-sm font-semibold text-red-500">
                            ⚠ Überschneidung im Dienstplan
                        </div>
                    </div>
                </div>
            </div>

            <UModal v-model:open="isShiftModalOpen" title="Schicht hinzufügen">
                <template #body>
                    <div class="space-y-4 text-base">
                        <label class="flex flex-col gap-2 text-base font-semibold text-default">
                            Datum
                            <UInput v-model="shiftForm.date" type="date" size="lg" />
                        </label>
                        <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                            <label class="flex flex-col gap-2 text-base font-semibold text-default">
                                Beginn
                                <UInput v-model="shiftForm.start_time" type="time" size="lg" />
                            </label>
                            <label class="flex flex-col gap-2 text-base font-semibold text-default">
                                Ende
                                <UInput v-model="shiftForm.end_time" type="time" size="lg" />
                            </label>
                        </div>
                        <label class="flex flex-col gap-2 text-base font-semibold text-default">
                            Bezeichnung (optional)
                            <UInput v-model="shiftForm.label" placeholder="z.B. Verkauf" size="lg" />
                        </label>
                        <label class="flex flex-col gap-2 text-base font-semibold text-default">
                            Notiz (optional)
                            <textarea v-model="shiftForm.notes" rows="3"
                                class="w-full rounded-lg border border-default bg-elevated px-3 py-2 text-base text-default"></textarea>
                        </label>

                        <div class="flex flex-wrap justify-end gap-3">
                            <UButton size="lg" color="neutral" variant="outline" label="Abbrechen"
                                @click="isShiftModalOpen = false" />
                            <UButton size="lg" color="primary" label="Speichern" @click="saveShift" />
                        </div>
                    </div>
                </template>
            </UModal>

            <UModal v-model:open="isAssignModalOpen" title="Mitarbeiter hinzufügen">
                <template #body>
                    <div class="space-y-4 text-base">
                        <div class="rounded-xl border border-default bg-muted/30 px-4 py-3">
                            <div class="text-sm text-muted">Schicht</div>
                            <div class="text-lg font-semibold text-default">
                                {{ assignContext?.date }} · {{ assignContext?.start_time }} – {{ assignContext?.end_time
                                }}
                            </div>
                            <div v-if="assignContext?.label" class="text-sm text-muted">{{ assignContext?.label }}</div>
                        </div>

                        <label class="flex flex-col gap-2 text-base font-semibold text-default">
                            Mitarbeiter suchen
                            <UInput v-model="employeeSearch" placeholder="Name eingeben" size="lg" />
                        </label>

                        <div
                            class="max-h-56 space-y-4 overflow-y-auto rounded-xl border border-default bg-elevated p-3">
                            <div v-if="groupedEmployees.available.length">
                                <div class="text-sm font-semibold text-muted">Verfügbar</div>
                                <label v-for="employee in groupedEmployees.available" :key="employee.id"
                                    class="mt-2 flex items-center gap-3 rounded-lg px-2 py-2 text-base text-default">
                                    <input v-model="selectedEmployeeIds" type="checkbox" :value="employee.id"
                                        class="h-5 w-5 rounded border-default" />
                                    <span>{{ employee.name }}</span>
                                </label>
                            </div>

                            <div v-if="groupedEmployees.partial.length">
                                <div class="text-sm font-semibold text-muted">Teilweise verfügbar</div>
                                <label v-for="employee in groupedEmployees.partial" :key="employee.id"
                                    class="mt-2 flex items-center gap-3 rounded-lg px-2 py-2 text-base text-default">
                                    <input v-model="selectedEmployeeIds" type="checkbox" :value="employee.id"
                                        class="h-5 w-5 rounded border-default" />
                                    <span>{{ employee.name }}</span>
                                    <span class="text-sm text-muted">
                                        ({{ employee.partial.map((item) => `${item.start_time}–${item.end_time}`).join(', ') }})
                                    </span>
                                </label>
                            </div>

                            <div v-if="groupedEmployees.unavailable.length">
                                <div class="text-sm font-semibold text-muted">Nicht verfügbar</div>
                                <label v-for="employee in groupedEmployees.unavailable" :key="employee.id"
                                    class="mt-2 flex items-center gap-3 rounded-lg px-2 py-2 text-base text-default">
                                    <input v-model="selectedEmployeeIds" type="checkbox" :value="employee.id"
                                        class="h-5 w-5 rounded border-default" />
                                    <span>{{ employee.name }}</span>
                                </label>
                            </div>

                            <div v-if="groupedEmployees.unknown.length">
                                <div class="text-sm font-semibold text-muted">Unbekannt</div>
                                <label v-for="employee in groupedEmployees.unknown" :key="employee.id"
                                    class="mt-2 flex items-center gap-3 rounded-lg px-2 py-2 text-base text-default">
                                    <input v-model="selectedEmployeeIds" type="checkbox" :value="employee.id"
                                        class="h-5 w-5 rounded border-default" />
                                    <span>{{ employee.name }}</span>
                                </label>
                            </div>
                        </div>

                        <div class="flex flex-wrap justify-end gap-3">
                            <UButton size="lg" color="neutral" variant="outline" label="Abbrechen"
                                @click="closeAssignModal" />
                            <UButton size="lg" color="primary" label="Speichern" @click="saveAssignments" />
                        </div>
                    </div>
                </template>
            </UModal>

            <UModal v-model:open="isAutoScheduleModalOpen" title="Plan automatisch erstellen">
                <template #body>
                    <div class="space-y-6">
                        <div class="flex flex-wrap gap-4">
                            <label class="flex flex-col gap-2 text-base font-semibold text-default">
                                Von
                                <UInput v-model="autoScheduleForm.from" type="date" size="lg" />
                            </label>
                            <label class="flex flex-col gap-2 text-base font-semibold text-default">
                                Bis
                                <UInput v-model="autoScheduleForm.to" type="date" size="lg" />
                            </label>
                        </div>

                        <div class="rounded-xl border border-default bg-muted/30 p-4">
                            <div class="text-base font-semibold text-default">Optionen</div>
                            <div class="mt-3 space-y-3 text-base text-default">
                                <label class="flex items-center gap-3">
                                    <input v-model="autoScheduleForm.options.respect_availability" type="checkbox"
                                        class="h-5 w-5" />
                                    Verfügbarkeiten beachten
                                </label>
                                <label class="flex items-center gap-3">
                                    <input v-model="autoScheduleForm.options.avoid_overlaps" type="checkbox"
                                        class="h-5 w-5" />
                                    Überschneidungen vermeiden
                                </label>
                                <label class="flex items-center gap-3">
                                    <input v-model="autoScheduleForm.options.fair_distribution" type="checkbox"
                                        class="h-5 w-5" />
                                    Fair verteilen
                                </label>
                            </div>
                        </div>

                        <div v-if="autoScheduleResult" class="rounded-xl border border-default bg-elevated p-4">
                            <div class="text-base font-semibold text-default">Ergebnis</div>
                            <div class="mt-2 text-lg font-semibold text-default">
                                {{ autoScheduleResult.assigned.length }} Schichten belegt
                            </div>
                            <div class="text-lg font-semibold text-default">
                                {{ autoScheduleResult.unfilled.length }} Schichten offen
                            </div>
                        </div>

                        <div class="flex flex-wrap gap-3">
                            <UButton size="lg" color="neutral" variant="outline" label="Abbrechen"
                                @click="isAutoScheduleModalOpen = false" />
                            <UButton size="lg" color="primary" label="Vorschlag erstellen"
                                :loading="isAutoScheduleLoading" @click="runAutoSchedule(false)" />
                            <UButton v-if="autoScheduleResult" size="lg" color="primary" variant="outline"
                                label="Übernehmen" :loading="isAutoScheduleLoading" @click="runAutoSchedule(true)" />
                        </div>
                    </div>
                </template>
            </UModal>
        </template>
    </UDashboardPanel>
</template>
