"use client";

import React, { memo, useCallback, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { Button } from "../ui/button";
import { CircleX, Minus, Plus, Trash2 } from "lucide-react";
import { Separator } from "../ui/separator";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { useCartStore } from "@/hooks/useCartStore";
import { CartItem } from "@/types/cart";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { toast } from "sonner";
import { formatCurrency } from "@/lib/format";

interface CartItemRowProps {
  item: CartItem;
  onUpdateQuantity: (id: string, quantity: number) => void;
  onDeleteRequest: (id: string) => void;
}

/*
  ⚡ Optimization: Memoized List Item
  Wrapping the individual row in React.memo prevents it from re-rendering
  when other items in the cart are updated.
*/
const CartItemRow = memo(({ item, onUpdateQuantity, onDeleteRequest }: CartItemRowProps) => {
  return (
    <div key={item.id}>
      <div className="flex justify-between">
        <div className="p-4 flex">
          {/*
            ⚡ Optimization: Responsive Images
            Added 'sizes' attribute to ensure appropriately scaled images are served.
            Fixed width/height matches the UI constraints.
          */}
          <Image
            src={item.image}
            alt={item.name}
            width={120}
            height={120}
            sizes="120px"
            className="rounded-lg object-cover"
          />
          <div className="px-4 py-2">
            <Link href={`/product/${item.id}`} className="text-xl hover:underline">
              {item.name}
            </Link>
            <p className="text-sm text-neutral-800">
              {formatCurrency(item.price)}
            </p>
            <div className="rounded-full flex items-center justify-center border border-dark-blue-500 mt-4">
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    size="icon"
                    variant="ghost"
                    className="rounded-full"
                aria-label={
                  item.quantity <= 1
                    ? "Produkt löschen"
                    : "Anzahl verringern"
                }
                onClick={() => {
                  if (item.quantity <= 1) {
                    onDeleteRequest(item.id);
                  } else {
                    onUpdateQuantity(item.id, item.quantity - 1);
                  }
                }}
              >
                {item.quantity <= 1 ? (
                  <Trash2 size={20} aria-hidden="true" />
                ) : (
                  <Minus size={20} aria-hidden="true" />
                )}
              </Button>
                </TooltipTrigger>
                <TooltipContent>
                  {item.quantity <= 1 ? "Produkt löschen" : "Anzahl verringern"}
                </TooltipContent>
              </Tooltip>
              <span className="px-4 font-medium">{item.quantity}</span>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    size="icon"
                    variant="ghost"
                    className="rounded-full"
                    aria-label="Anzahl erhöhen"
                    onClick={() =>
                      onUpdateQuantity(item.id, item.quantity + 1)
                    }
                  >
                    <Plus size={20} aria-hidden="true" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>Anzahl erhöhen</TooltipContent>
              </Tooltip>
            </div>
          </div>
          <div>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  size="icon"
                  variant="ghost"
                  className="rounded-full"
                  aria-label="Produkt entfernen"
                  onClick={() => onDeleteRequest(item.id)}
                >
                  <CircleX size={20} aria-hidden="true" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Produkt entfernen</TooltipContent>
            </Tooltip>
          </div>
        </div>
        <div className="flex items-center justify-center px-4">
          <div className="font-medium">
            {formatCurrency(item.quantity * item.price)}
          </div>
        </div>
      </div>
      <Separator />
    </div>
  );
});

CartItemRow.displayName = "CartItemRow";

export const CartItemList = () => {
  const [lastAnnouncement, setLastAnnouncement] = useState("");
  /*
    ⚡ Optimization: Selective Zustand Selectors
    Only subscribe to 'items' and specific actions to prevent re-renders when
    unrelated store state (e.g., 'isOpen') changes.
  */
  const items = useCartStore((state) => state.items);
  const removeFromCart = useCartStore((state) => state.removeFromCart);
  const updateQuantity = useCartStore((state) => state.updateQuantity);
  const addToCart = useCartStore((state) => state.addToCart);

  const [itemToDelete, setItemToDelete] = useState<string | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);

  /*
    ⚡ Optimization: Stable Event Handlers
    Wrapping handlers in useCallback ensures that CartItemRow doesn't re-render
    due to handler reference changes.
  */
  const handleDeleteRequest = useCallback((itemId: string) => {
    setItemToDelete(itemId);
    setIsDialogOpen(true);
  }, []);

  const handleUpdateQuantity = useCallback((id: string, quantity: number) => {
    updateQuantity(id, quantity);
    const item = items.find((i) => i.id === id);
    if (item) {
      setLastAnnouncement(`Anzahl von ${item.name} auf ${quantity} aktualisiert`);
    }
  }, [updateQuantity, items]);

  const confirmDelete = useCallback(() => {
    if (itemToDelete) {
      const item = items.find((i) => i.id === itemToDelete);
      if (item) {
        // Speichere das gelöschte Produkt
        const deletedItem = { ...item }; // Lokale Kopie erstellen
        removeFromCart(itemToDelete);

        // Zeige Toast-Benachrichtigung mit "Rückgängig"-Option
        toast.info("Produkt wurde gelöscht", {
          description: `${item.name} wurde aus dem Warenkorb entfernt.`,

          action: {
            label: "Rückgängig",
            onClick: () => {
              // Verwende die lokale Kopie, um Race Conditions zu vermeiden
              addToCart(deletedItem);
            },
          },
        });
      }
      setItemToDelete(null);
      setIsDialogOpen(false);
    }
  }, [addToCart, itemToDelete, items, removeFromCart]);

  return (
    <div>
      <div className="sr-only" aria-live="polite" role="status">
        {lastAnnouncement}
      </div>
      {items.map((item) => (
        <CartItemRow
          key={item.id}
          item={item}
          onUpdateQuantity={handleUpdateQuantity}
          onDeleteRequest={handleDeleteRequest}
        />
      ))}
      <AlertDialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              Produkt aus dem Warenkorb entfernen?
            </AlertDialogTitle>
            <AlertDialogDescription>
              Möchten Sie{" "}
              <span className="font-semibold">
                {items.find((i) => i.id === itemToDelete)?.name}
              </span>{" "}
              wirklich entfernen? Sie können diese Aktion über die
              Benachrichtigung rückgängig machen.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setItemToDelete(null)}>
              Abbrechen
            </AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete}>
              Löschen
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};
