"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";
import { Heart, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { EmptyState } from "@/components/ui/section";
import { formatCurrency } from "@/lib/utils";

const WISHLIST_KEY = "305g_wishlist";

type WishlistItem = {
  id: string;
  name: string;
  slug: string;
  price: number;
  thumbnail?: string | null;
};

export function WishlistClient() {
  const [items, setItems] = useState<WishlistItem[]>([]);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    try {
      const raw = localStorage.getItem(WISHLIST_KEY);
      setItems(raw ? (JSON.parse(raw) as WishlistItem[]) : []);
    } catch {
      setItems([]);
    } finally {
      setReady(true);
    }
  }, []);

  function remove(id: string) {
    const next = items.filter((item) => item.id !== id);
    setItems(next);
    localStorage.setItem(WISHLIST_KEY, JSON.stringify(next));
  }

  if (!ready) return <div className="h-40 animate-pulse rounded-2xl bg-surface" />;

  if (!items.length) {
    return (
      <div className="space-y-4">
        <EmptyState
          title="Wishlist masih kosong"
          description="Tambahkan produk favorit dari halaman detail produk (fitur akan tersimpan di perangkat)."
        />
        <div className="flex flex-wrap gap-3">
          <Button href="/products">
            <Heart className="h-4 w-4" />
            Jelajahi produk
          </Button>
        </div>
      </div>
    );
  }

  return (
    <ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
      {items.map((item) => (
        <li key={item.id} className="overflow-hidden rounded-2xl border border-border bg-surface">
          <div className="relative aspect-[16/10] bg-surface-2">
            {item.thumbnail ? (
              <Image src={item.thumbnail} alt={item.name} fill className="object-cover" sizes="33vw" />
            ) : null}
          </div>
          <div className="space-y-3 p-4">
            <Link href={`/product/${item.slug}`} className="font-semibold hover:text-accent">
              {item.name}
            </Link>
            <p className="text-accent">{formatCurrency(item.price)}</p>
            <div className="flex gap-2">
              <Button href={`/product/${item.slug}`} size="sm" className="flex-1">
                Lihat
              </Button>
              <button
                type="button"
                aria-label="Hapus dari wishlist"
                onClick={() => remove(item.id)}
                className="rounded-xl border border-border px-3 text-muted hover:text-danger"
              >
                <Trash2 className="h-4 w-4" />
              </button>
            </div>
          </div>
        </li>
      ))}
    </ul>
  );
}
