"use client";
import React, { useEffect, useState } from "react";
import { Separator } from "../ui/separator";
import { Button } from "../ui/button";
import { CartItemList } from "./CartItemList";
import { ArrowRight, Trash2 } from "lucide-react";
import { useCartStore } from "@/hooks/useCartStore";
import Link from "next/link";
import { EmptyCartFallback } from "./EmptyCartFallback";
import { formatCurrency } from "@/lib/format";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { toast } from "sonner";

export const CartDetails = () => {
  /*
    ⚡ Optimization: Selective Zustand Selectors
    Prevents re-renders of the entire checkout summary when unrelated store state changes.
  */
  const items = useCartStore((state) => state.items);
  const clearCart = useCartStore((state) => state.clearCart);
  const addToCart = useCartStore((state) => state.addToCart);
  const totalPrice = useCartStore((state) =>
    state.items.reduce((total, item) => total + item.price * item.quantity, 0)
  );
  const totalItemsCount = useCartStore((state) =>
    state.items.reduce((total, item) => total + item.quantity, 0)
  );

  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  const handleClearCart = () => {
    // Speichere den aktuellen Zustand des Warenkorbs
    const currentCartState = [...items]; // Lokale Kopie erstellen
    clearCart();

    // Zeige Toast-Benachrichtigung mit "Rückgängig"-Option
    toast("Warenkorb geleert", {
      description: "Ihr Warenkorb wurde geleert.",
      action: {
        label: "Rückgängig",
        onClick: () => {
          // Stelle den vorherigen Zustand des Warenkorbs wieder her
          currentCartState.forEach((item) => addToCart(item));
        },
      },
    });
  };

  if (!isMounted) {
    // Render a loading state or placeholder during hydration
    return (
      <div className="min-h-screen flex flex-col items-center justify-center">
        <div className="animate-spin rounded-full h-16 w-16 border-t-4 border-blue-500 border-solid"></div>
        <p className="mt-4 text-lg font-medium text-gray-600">
          Wird geladen...
        </p>
      </div>
    );
  }

  return (
    <>
      {totalItemsCount > 0 ? (
        <div>
          <div className="flex items-center">
            <h1 className="p-4 text-xl font-semibold">Mein Warenkorb</h1>
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button
                  className="m-4"
                  size="icon"
                  variant="ghost"
                  aria-label="Warenkorb leeren"
                >
                  <Trash2 />
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>
                    Möchten Sie Ihren Warenkorb wirklich leeren?
                  </AlertDialogTitle>
                  <AlertDialogDescription>
                    Diese Aktion kann nicht rückgängig gemacht werden, es sei
                    denn, Sie klicken auf &quot;Rückgängig&quot; in der
                    Benachrichtigung.
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Abbrechen</AlertDialogCancel>
                  <AlertDialogAction onClick={handleClearCart}>
                    Leeren
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
            <div className="flex-1 text-center">
              <h2 className="pr-20 font-semibold">Mengenpreis</h2>
            </div>
          </div>
          <div className="flex justify-stretch">
            <div className="w-3/5">
              <Separator />
              <CartItemList />
            </div>
            <Separator orientation="vertical" className="h-auto m-4" />
            <div className="w-1/3">
              <Separator />
              <div className="py-4 px-3">
                <div className="flex justify-between mb-2 mt-1">
                  <p>Zwischensumme: </p>
                  <p>{formatCurrency(totalPrice)}</p>
                </div>
                <div className="flex justify-between my-2">
                  <p>Versandkosten: </p>
                  <p>0,00 €</p>
                </div>
                <div className="flex justify-between my-2 font-bold">
                  <p>Gesamt: </p>
                  <p>{formatCurrency(totalPrice)}</p>
                </div>
                <Separator />
                <div className="flex justify-center">
                  <Button className="w-auto m-2" asChild>
                    <Link href="/order/checkout">
                      Zur Kasse
                      <ArrowRight className="ml-2 h-4 w-4" />
                    </Link>
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <EmptyCartFallback />
      )}
    </>
  );
};
