"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardFooter } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Trash, ShoppingCart, Loader2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import Link from "next/link";
import Image from "next/image";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "@/redux/store";
import {
  fetchWishlistFromBackend,
  removeWishlistItemFromBackend,
} from "@/redux/slices/wishlistSlice";
import { toast } from "react-toastify";
import PriceDisplay from "@/components/ui/formattedPrice";
import {
  addItemToBackendCart,
  addItemToCart,
} from "@/redux/slices/cartSlice";
import { useSession } from "next-auth/react";

export function WishlistGrid() {
  const dispatch = useDispatch<AppDispatch>();
  const wishlist = useSelector((state: RootState) => state.wishlist);
  const { data: session } = useSession();

  const wishlistItems = wishlist.WishListItem || [];
  const [hydration, setHydration] = useState(true);

  useEffect(() => {
    dispatch(fetchWishlistFromBackend());
    setHydration(false);
  }, [dispatch]);


  const handleRemoveFromWishList = (uuid: string) => {
    dispatch(removeWishlistItemFromBackend(uuid));
    toast.success("Item has been removed from wishlist");
  };

  const handleAddToCart = (variant: ProductVariant) => {
    if (session?.user.uuid) {
      dispatch(addItemToBackendCart(parseInt(variant.id)));
    } else {
      dispatch(addItemToCart(variant));
    }
    toast.success("Item has been added to cart");
  };

  if (hydration) {
    return (
      <div className="flex justify-center items-center min-h-[200px]">
        <Loader2 className="animate-spin w-6 h-6 text-gray-500" />
      </div>
    );
  }

  if (wishlistItems.length === 0) {
    return (
      <div className="rounded-lg border border-dashed p-8 text-center max-w-md mx-auto mt-10 shadow-md">
        <h3 className="text-xl font-semibold">Your wishlist is empty</h3>
        <p className="mt-2 text-sm text-muted-foreground">
          Start saving products you like for later.
        </p>
        <Button className="mt-4" asChild>
          <Link href="/">Browse Products</Link>
        </Button>
      </div>
    );
  }

  return (
    <div className="grid gap-6 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 mt-6 px-4 md:px-0">
      {wishlistItems.map((item: WishlistItem) => (
        <Card
          key={item.id}
          className="overflow-hidden shadow-sm hover:shadow-md transition-all"
        >
          <div className="relative bg-muted h-48 md:h-52 lg:h-56">
            {item.variant.variant_images?.length > 0 ? (
              <Image
                width={500}
                height={500}
                src={item.variant.variant_images[0].file_url}
                alt={item.variant.name}
                className="object-contain w-full h-full p-4"
              />
            ) : (
              <div className="flex items-center justify-center h-full text-sm text-gray-400">
                No Image
              </div>
            )}
          </div>

          <CardContent className="p-4">
            <h3 className="font-semibold text-sm md:text-base line-clamp-1">
              {item.variant.name}
            </h3>
            <div className="flex items-center justify-between mt-2">
              <p className="font-medium text-primary">
                <PriceDisplay price={item.variant.special_price} />
              </p>
              {item.variant.quantity <= 0 && (
                <Badge
                  variant="outline"
                  className="bg-red-100 text-red-800 text-xs"
                >
                  Out of Stock
                </Badge>
              )}
            </div>
          </CardContent>

          <CardFooter className="p-4 pt-0 flex justify-between gap-2">
            <Button
              size="sm"
              className="flex-1 bg-primary hover:bg-primary/90 text-white"
              onClick={() => handleAddToCart(item.variant)}
              disabled={!item.variant.quantity || item.variant.quantity <= 0}
            >
              <ShoppingCart className="mr-2 h-4 w-4" />
              Add to Cart
            </Button>

            <Button
              variant="ghost"
              size="icon"
              onClick={() => handleRemoveFromWishList(item.uuid)}
            >
              <Trash className="h-4 w-4 hover:text-red-500" />
              <span className="sr-only">Remove</span>
            </Button>
          </CardFooter>
        </Card>
      ))}
    </div>
  );
}
