import { useMeals, type Meal } from "~/lib/api";
import { DailyMenu } from "./menu-card";
import { DateTime } from "luxon";
import { useState } from "react";
import DayNavigation from "./day-navigation";

export default function Menus() {
  const { isLoading, error, meals } = useMeals();
  const [date, setDate] = useState(DateTime.now().startOf("day"));

  const findMenuForDate = (date: DateTime) => {
    return meals?.filter((meal) => {
      const mealDate = DateTime.fromISO(meal.date);
      return mealDate.hasSame(date.toLocal(), "day");
    });
  };

  return (
    <div className="space-y-4">
      {isLoading && <p>Chargement du menu...</p>}
      {error && (
        <p className="text-red-500">Erreur lors du chargement des menus.</p>
      )}
      {meals && meals.length === 0 && <p>Aucun menu disponible.</p>}

      {/* Menus */}
      <DayNavigation startDate={date} setStartDate={setDate} />
      <DailyMenu meals={findMenuForDate(date) || ([] as Meal[])} />
    </div>
  );
}
