"use client"

import {useEffect, useState} from "react";
import {DateTime} from "luxon";
import ScheduleCalendar from "@/components/features/schedule/ScheduleCalendar";
import PageTitle from "@/components/ui/PageTitle";
import {ScheduleType} from "@/types/ScheduleType";
import Spinner from "@/components/Spinner";
import {listSchedule} from "@/utils/api/scheduleApi";

const HistoricalDishes = () => {
    const [schedule, setSchedule] = useState<ScheduleType[]>([]);
    const [isLoading, setIsLoading] = useState(true);

    const yesterday = DateTime.now().minus({ days: 1 }).toFormat('yyyy-LL-dd');

    useEffect(() => {
        listSchedule(undefined, yesterday)
            .then((dishes: ScheduleType[]) => dishes
                .sort((a: ScheduleType, b: ScheduleType) => new Date(b.date).getTime() - new Date(a.date).getTime())
            )
            .then((dishes) => setSchedule(dishes))
            .finally(() => setIsLoading(false))
    }, [yesterday]);

    if (isLoading) {
        return <Spinner />;
    }

    if (!schedule || Object.keys(schedule).length === 0) {
        return (
            <div className="w-full text-center text-2xl border-white border-2 rounded-xl mt-4">
                No dishes scheduled
            </div>
        );
    }

    return <div className="justify-items-center">
        <PageTitle>History</PageTitle>
        <ScheduleCalendar schedule={schedule as ScheduleType[]} />
    </div>
}

export default HistoricalDishes