"use client";

import PageTitle from "@/components/ui/PageTitle";
import {DishType} from "@/types/DishType";
import Dish from "@/components/features/dishes/Dish";
import {PlusIcon} from "@heroicons/react/24/solid";
import {useEffect, useState} from "react";
import useRoutes from "@/hooks/useRoutes";
import {listDishes} from "@/utils/api/dishApi";
import Button from "@/components/ui/Button"
export const dynamic = 'force-dynamic';

export default function DishesIndexPage() {
    const routes = useRoutes();

    const [dishes, setDishes] = useState<DishType[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        listDishes()
            .then((dishes: DishType[]) => setDishes(dishes))
            .finally(() => setLoading(false));
    }, []);

    if (loading) return <p>Loading...</p>;

    if (! dishes) {
        return <h1>Loading...</h1>
    }

    return (
        <>
            <div className="flex mb-3">
                <div className="flex-none mr-4 pt-1">
                    <PageTitle>Dishes</PageTitle>
                </div>
                <div className="flex-grow flex justify-end">
                    <Button
                        href={routes.dish.create()}
                        icon={<PlusIcon />}
                        size="small"
                        variant="primary"
                        appearance="text"
                    >
                        Add Dish
                    </Button>
                </div>
            </div>

            {
                dishes.length === 0
                    ? <h1 className="text-secondary">No dishes found :(</h1>
                    : dishes.map((dish: DishType, index: number) => <Dish key={index} dish={dish}/>)
            }
        </>
    );
}
