"use client"

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

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

    const today = DateTime.now().toFormat("yyyy-LL-dd");

    const fetchSchedule = useCallback(() => {
        setIsLoading(true);
        listSchedule(today)
            .then((dishes) => setSchedule(dishes))
            .finally(() => setIsLoading(false));
    }, [today]);

    useEffect(() => {
        fetchSchedule();
    }, [fetchSchedule]);

    const { users, isLoading: areUsersLoading } = useFetchUsers();
    const { dishes, isLoading: areDishesLoading } = useFetchDishes();

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

    if (users.length === 0 || dishes.length === 0) {
        return <OnboardingBanner dishes={dishes} users={users} />
    }

    return (
        <div className="justify-items-center">
            <div className="flex w-full py-2">
                <div className="flex-none w-1/2 text-left pt-1">
                    <PageTitle>Schedule</PageTitle>
                </div>
                <div className="flex-none w-1/2 text-right">
                    <ScheduleRegenerateButton onModalClose={fetchSchedule} />
                </div>
            </div>
            {
                !schedule || Object.keys(schedule).length === 0
                    ? <div className="w-full text-center text-2xl border-white border-2 rounded-xl mt-4">No dishes scheduled</div>
                    : <ScheduleCalendar schedule={schedule as ScheduleType[]} />
            }
        </div>
    );
};

export default UpcomingDishes;