"use client"

import {FC} from "react";
import ScheduleDayCard from "@/components/features/schedule/dayCard/ScheduleDayCard";
import { FilledScheduleType, ScheduleType } from "@/types/ScheduleType";
import {useFetchUsers} from "@/hooks/useFetchUsers";
import Spinner from "@/components/Spinner";

const generateDates = (startDate: string, days: number): string[] => {
    const dates = [];
    const start = new Date(startDate);

    for (let i = 0; i < days; i++) {
        const currentDate = new Date(start);
        currentDate.setDate(start.getDate() + i);
        dates.push(currentDate.toISOString().split('T')[0]);
    }

    return dates;
};


const fillCalendar = (schedules: ScheduleType[]): FilledScheduleType[] => {
    /*
Array(14)
    0:
        date: "2025-05-05"
        id: 2
        is_skipped: false
        scheduled_user_dishes: []
     */

    const dates = generateDates((new Date()).toISOString().split('T')[0], 31)

    return dates.map((date): FilledScheduleType => {
        console.log(date)

        const schedule = schedules.find((schedule: ScheduleType) => schedule.date == date)

        if (schedule) {
            return schedule
        }

        return {
            date,
            scheduled_user_dishes: []
        }
    })
}

interface Props {
    schedule: ScheduleType[];
}

const ScheduleCalendar: FC<Props> = ({ schedule }: Props) => {
    const {users, isLoading: areUsersLoading} = useFetchUsers();

    if (areUsersLoading) return <Spinner />

    const fullCalendar = fillCalendar(schedule)

    return (
        <div className="w-full flex flex-col items-start">
            { fullCalendar.map((schedule, index) => (
                <ScheduleDayCard
                    key={index}
                    schedule={schedule}
                    users={users}
                />
            ))}
        </div>
    )
}

export default ScheduleCalendar