"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { Heart, Loader2, ShoppingCart } from "lucide-react";
import { formatPrice } from "@/lib/utils";
import { useCartStore } from "@/store/cart";
import toast from "react-hot-toast";

interface WishlistProduct {
  id: string; productId: string;
  product: { id: string; name: string; slug: string; price: number; images: string[]; stock: number; brand: { name: string } };
}

export default function WishlistPage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [items, setItems] = useState<WishlistProduct[]>([]);
  const [loading, setLoading] = useState(true);
  const { addItem } = useCartStore();

  useEffect(() => {
    if (status === "unauthenticated") { router.push("/login"); return; }
    if (status === "authenticated") setLoading(false);
  }, [status, router]);

  if (loading) return <div className="flex justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-sky-500" /></div>;

  return (
    <div className="max-w-3xl mx-auto px-4 py-8">
      <div className="flex items-center gap-3 mb-8">
        <div className="w-10 h-10 rounded-xl bg-red-100 flex items-center justify-center">
          <Heart className="w-5 h-5 text-red-500" />
        </div>
        <div>
          <h1 className="text-2xl font-black text-slate-900">My Wishlist</h1>
          <p className="text-slate-500 text-sm">{items.length} saved items</p>
        </div>
      </div>

      {items.length === 0 ? (
        <div className="text-center py-20">
          <Heart className="w-16 h-16 text-slate-200 mx-auto mb-4" />
          <h2 className="text-xl font-bold text-slate-700 mb-2">Your wishlist is empty</h2>
          <p className="text-slate-500 mb-6">Save products you love for later</p>
          <Link href="/" className="bg-sky-500 text-white px-8 py-3 rounded-xl font-bold hover:bg-sky-600 transition-colors">Browse Products</Link>
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2">
          {items.map((item) => (
            <div key={item.id} className="bg-white rounded-2xl border border-slate-100 overflow-hidden hover:border-sky-200 transition-colors">
              <div className="relative aspect-video bg-slate-50">
                <Image src={item.product.images[0] || "/images/placeholder.png"} alt={item.product.name} fill className="object-cover" />
              </div>
              <div className="p-4">
                <p className="text-xs text-sky-600 font-bold mb-1">{item.product.brand.name}</p>
                <Link href={`/products/${item.product.slug}`} className="font-bold text-slate-800 hover:text-sky-700 line-clamp-2 text-sm">{item.product.name}</Link>
                <p className="text-lg font-black text-slate-900 mt-2">{formatPrice(item.product.price)}</p>
                <div className="flex gap-2 mt-3">
                  <button onClick={() => { addItem({ id: item.product.id, name: item.product.name, price: item.product.price, image: item.product.images[0], slug: item.product.slug, stock: item.product.stock }); toast.success("Added to cart!"); }}
                    className="flex-1 flex items-center justify-center gap-2 bg-sky-500 text-white py-2.5 rounded-xl text-sm font-bold hover:bg-sky-600 transition-colors">
                    <ShoppingCart className="w-4 h-4" /> Add to Cart
                  </button>
                  <button onClick={() => setItems((prev) => prev.filter((i) => i.id !== item.id))}
                    className="p-2.5 rounded-xl border border-red-200 text-red-500 hover:bg-red-50 transition-colors">
                    <Heart className="w-4 h-4 fill-red-500" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
