<script lang="ts">
    import { CalendarView } from "fluent-svelte"
    import type { Writable } from "svelte/store"


    export let groupTitle: string
    export let datePickerProps: DatePickerProps
    export let formValues: Writable<FormValues>
    export let rowNr: number
    export let formCol: FormColumn

    const today = new Date()
    const oneYearFromNow = new Date(today)
    oneYearFromNow.setFullYear(today.getFullYear() + 1)
    const indexToDay: Record<number, string> = {
        0: "sunday",
        1: "monday",
        2: "tuesday",
        3: "wednesday",
        4: "thursday",
        5: "friday",
        6: "saturday",
    }

    function generateBlackoutDates(props: DatePickerProps): Date[] {
        let blackoutDates = []

        // Funktion, um einen ISO-String in ein vereinfachtes Date-Objekt umzuwandeln
        const dateFromISOString = (isoString: string) => {
            const date = new Date(isoString)
            return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
        }

        const dayToIndex: Record<string, number> = {
            sunday: 0,
            monday: 1,
            tuesday: 2,
            wednesday: 3,
            thursday: 4,
            friday: 5,
            saturday: 6,
        }

        // Initialisiere ein aktuelles Datum auf heute
        let currentDate = new Date(Date.UTC(today.getFullYear(), today.getMonth(), today.getDate()))

        // Schleife durch die nächsten 365 Tage
        for (let i = 0; i <= 365; i++) {
            // Überprüfen, ob dieses Datum erlaubt ist
            const isAllowed = props.allowedDateRanges.some((range) => {
                const fromDate = dateFromISOString(range.from)
                const toDate = dateFromISOString(range.to)

                return currentDate >= fromDate && currentDate <= toDate
            })

            // Überprüfen, ob der Wochentag ausgeschlossen ist
            const currentDayIndex = currentDate.getUTCDay()
            const currentDayString = indexToDay[currentDayIndex]
            const isExcluded = props.excludeDays?.includes(currentDayString)

            // Wenn nicht erlaubt oder ausgeschlossen, zu den Blackout-Daten hinzufügen
            if (!isAllowed || isExcluded) {
                blackoutDates.push(new Date(currentDate))
            }

            // Zum nächsten Tag wechseln
            currentDate.setUTCDate(currentDate.getUTCDate() + 1)
        }

        return blackoutDates
    }

    let value = new Date()
    const blackoutDates = generateBlackoutDates(datePickerProps)

    function setFormValues() {
        $formValues[`datepicker_${groupTitle}_${rowNr}_${formCol.datePickerEmailTitle}`] = {
            value: value.toLocaleDateString("de-DE"),
            required: !formCol.datePickerNotRequired,
        }
    }
    //needs email conntection
    $: {
        if (value) {
            setFormValues()
        }
    }
</script>

<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div class="container">
    <div
        class="datepicker"
        on:click|preventDefault|stopPropagation
        on:keydown|stopPropagation
        on:submit|stopPropagation|preventDefault
    >
        <CalendarView
            weekStart="{1}"
            bind:vaue="{value}"
            on:change="{(e) => {
                value = e.detail
            }}"
            min="{today}"
            max="{oneYearFromNow}"
            blackout="{blackoutDates}"
            locale="de-DE"
        />
    </div>
</div>

<style lang="less">
    @import url("https://unpkg.com/fluent-svelte/theme.css");
    .container {
        width: 100%;
        display: flex;
        justify-content: flex-start;
        --fds-solid-background-quarternary: var(--background-color);
        --fds-text-primary: var(--normal-font-color);
        --fds-text-secondary: var(--normal-font-color-80);
        --fds-text-tertiary: var(--normal-font-color-50);
        --fds-text-disabled: var(--normal-font-color-30);
        --fds-accent-disabled: var(--opposite-bg-color-5);
        --fds-control-strong-stroke-default: var(--opposite-bg-color-80);
        .datepicker {
            width: fit-content;
            margin: 5px 0px;
            box-shadow: 0 0 25px 10px var(--opposite-bg-color-5);
        }
    }
</style>
