import { CalendarCheck, CheckCheck, Loader2 } from "lucide-react";
import { Button } from "../ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { registerForMeal, useMeals, type Meal } from "~/lib/api";
import { useState } from "react";
import { toast } from "sonner";
import { formatDate } from "./date-picker";
import { DateTime } from "luxon";

export default function MealRegistration({
  credentials,
}: {
  credentials: { username: string; password: string };
}) {
  const [isPosting, setLoading] = useState(false);
  const { isLoading, error, meals: rawMeals, refetch } = useMeals();

  const filterRegisteredMeals = (meals: Meal[]) => {
    return meals?.filter((meal) => meal.submittable);
  };
  const meals = filterRegisteredMeals(rawMeals || []);

  const handleRegister = async (id: number) => {
    try {
      await registerForMeal(id, credentials.username, credentials.password);
      await refetch();
      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="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 repas disponible.</p>}

      {/* Menus */}
      <div className="px-4 py-2">
        <h2 className="text-2xl font-bold mb-4">Inscription aux repas</h2>

        <Card 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">
                    <CalendarCheck className="inline h-5 w-5 mr-4 text-primary" />
                    Prochains Repas
                  </CardTitle>
                </div>
              </div>
            </div>
          </CardHeader>

          <CardContent className="pt-0 pb-4">
            {meals.map((meal, i) => (
              <>
                <div className="flex items-start gap-1 mt-4">
                  <h4 className="font-semibold text-primary mb-1">
                    Repas du {formatDate(DateTime.fromISO(meal.date))}
                  </h4>
                  <p className="text-sm text-muted-foreground leading-relaxed">
                    ({meal.name})
                  </p>
                </div>

                <div className="mb-4">
                  {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 à ce repas
                    </Button>
                  )}
                  {isPosting && !meal.isRegistered && (
                    <Button
                      variant="default"
                      className="hidden w-full mt-4 mb-1"
                      disabled
                    >
                      <Loader2 className="h-5 w-5 mr-2 animate-spin" />
                      Inscription en cours...
                    </Button>
                  )}
                  {!isPosting && !meal.isRegistered && meal.submittable && (
                    <Button
                      variant="default"
                      className="w-full mt-2 mb-1"
                      onClick={async () => {
                        setLoading(true);
                        await handleRegister(meal.id);
                      }}
                    >
                      <CalendarCheck className="h-5 w-5 mr-2" />
                      S'inscrire à ce repas
                    </Button>
                  )}
                </div>
                {i < meals.length - 1 && <hr className="my-2" />}
              </>
            ))}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
