import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
import {
  Utensils,
  Salad,
  Cake,
  CookingPot,
  Icon,
  Carrot,
  CalendarCheck,
  CheckCheck,
  Loader2,
} from "lucide-react";
import { cheese } from "@lucide/lab";
import { registerForMeal, type Meal } from "~/lib/api";
import { Button } from "../ui/button";
import { toast } from "sonner";
import { useState } from "react";
import { getSavedCredentials } from "./credentials";

const getCourseIcon = (courseName: string) => {
  const name = courseName.toLowerCase();
  if (name.includes("hors")) return <Salad className="h-6 w-6" />;
  if (name.includes("plat")) return <CookingPot className="h-6 w-6" />;
  if (name.includes("garniture")) return <Carrot className="h-6 w-6" />;
  if (name.includes("fromage"))
    return <Icon iconNode={cheese} className="h-6 w-6" />;
  if (name.includes("dessert")) return <Cake className="h-6 w-6" />;
  return <Utensils className="h-6 w-6" />;
};

export function DailyMenu({
  meals,
  refetchMeals,
}: {
  meals: Meal[];
  refetchMeals: () => Promise<any>;
}) {
  if (meals.length === 0) {
    return (
      <div className="flex items-center justify-center p-4">
        <p className="text-muted-foreground">
          Aucun menu disponible pour ce jour.
        </p>
      </div>
    );
  }

  const [isLoading, setLoading] = useState(false);
  const credentials = getSavedCredentials();

  const handleRegister = async (id: number) => {
    try {
      if (!credentials) {
        toast.error(
          "Veuillez d'abord enregistrer vos identifiants dans l'onglet BJRepas."
        );
        return;
      }
      await registerForMeal(id, credentials.username, credentials.password);
      await refetchMeals();
      setLoading(false);
    } catch (error) {
      console.error("Error registering for meal:", error);
      toast.error(
        "Une erreur est survenue lors de l'inscription au repas. Veuillez réessayer."
      );
    }
  };

  return (
    <div className="px-4 py-2">
      <h2 className="text-2xl font-bold mb-4">
        {meals.length > 1 ? "Menus" : "Menu"} du jour
      </h2>

      {meals.map((meal, mealIndex) => (
        <Card key={mealIndex} className="w-full mb-6">
          <CardHeader className="pb-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div>
                  <CardTitle className="text-xl2 font-bold text-foreground capitalize">
                    <Utensils className="inline h-5 w-5 mr-4 text-primary" />
                    {meal.name}
                  </CardTitle>
                </div>
              </div>
            </div>
          </CardHeader>

          <CardContent className="pt-0 pb-4">
            <div className="space-y-4">
              {meal.courses.map((course, courseIndex) => (
                <div key={courseIndex} className="flex items-start gap-3">
                  <div className="p-2 rounded-full bg-primary/10">
                    {getCourseIcon(course.name)}
                  </div>
                  <div className="flex-1 min-w-0">
                    <h4 className="text-sm font-semibold text-primary mb-1">
                      {course.name}
                    </h4>
                    <p className="text-sm text-muted-foreground leading-relaxed">
                      {course.description}
                    </p>
                  </div>
                </div>
              ))}
            </div>

            {meal.isRegistered && (
              <Button
                variant="outline"
                className="w-full bg-green-600 hover:bg-green-700 text-white mt-4 mb-1"
                // onClick={handleUnregister}
                disabled
              >
                <CheckCheck className="h-5 w-5 mr-2" />
                Vous êtes inscrit(e) à ce repas
              </Button>
            )}
            {credentials &&
              !meal.isRegistered &&
              meal.submittable &&
              (isLoading ? (
                <Button variant="default" className="w-full mt-4 mb-1" disabled>
                  <Loader2 className="h-5 w-5 mr-2 animate-spin" />
                  Inscription en cours...
                </Button>
              ) : (
                <Button
                  variant="default"
                  className="w-full mt-4 mb-1"
                  onClick={() => handleRegister(meal.id)}
                >
                  <CalendarCheck className="h-5 w-5 mr-2" />
                  S'inscrire à ce repas
                </Button>
              ))}
          </CardContent>
        </Card>
      ))}
    </div>
  );
}
