"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import { ShoppingCart, Trash2, Plus, Minus, ArrowRight, ShoppingBag, Package } from "lucide-react";

type CartItem = {
  productId: string;
  slug: string;
  name: string;
  price: number;
  quantity: number;
  image: string;
  variationId?: string;
};

export default function CartPage() {
  const [items, setItems] = useState<CartItem[]>([]);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    const raw = localStorage.getItem("kc_cart");
    if (raw) setItems(JSON.parse(raw));
    const onUpdate = () => {
      const r = localStorage.getItem("kc_cart");
      setItems(r ? JSON.parse(r) : []);
    };
    window.addEventListener("cart-updated", onUpdate);
    return () => window.removeEventListener("cart-updated", onUpdate);
  }, []);

  function persist(next: CartItem[]) {
    setItems(next);
    localStorage.setItem("kc_cart", JSON.stringify(next));
    window.dispatchEvent(new Event("cart-updated"));
  }

  function updateQty(key: string, delta: number) {
    const next = items.map(i => {
      if (i.productId + (i.variationId ?? "") === key) {
        return { ...i, quantity: Math.max(1, i.quantity + delta) };
      }
      return i;
    });
    persist(next);
  }

  function removeItem(key: string) {
    persist(items.filter(i => i.productId + (i.variationId ?? "") !== key));
  }

  const total = items.reduce((s, i) => s + i.price * i.quantity, 0);

  if (!mounted) return null;

  return (
    <div className="min-h-screen bg-neutral-50">
      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <h1 className="text-2xl font-bold text-navy-900 mb-8 flex items-center gap-3">
          <ShoppingCart size={24} /> Shopping Cart
          {items.length > 0 && <span className="text-base font-normal text-neutral-400">({items.length} item{items.length !== 1 ? "s" : ""})</span>}
        </h1>

        {items.length === 0 ? (
          <div className="bg-white rounded-2xl border border-neutral-200 p-20 text-center">
            <ShoppingBag size={56} className="mx-auto mb-5 text-neutral-200" />
            <h2 className="text-xl font-bold text-neutral-700 mb-2">Your cart is empty</h2>
            <p className="text-neutral-400 text-sm mb-6">Looks like you have not added anything to your cart yet.</p>
            <Link href="/shop" className="inline-flex items-center gap-2 px-6 py-3 bg-navy-700 text-white font-semibold rounded-xl hover:bg-navy-800 transition-colors">
              Continue Shopping <ArrowRight size={16} />
            </Link>
          </div>
        ) : (
          <div className="grid lg:grid-cols-3 gap-8">
            {/* Items */}
            <div className="lg:col-span-2 space-y-3">
              {items.map(item => {
                const key = item.productId + (item.variationId ?? "");
                return (
                  <div key={key} className="bg-white rounded-2xl border border-neutral-200 p-4 flex items-center gap-4">
                    <div className="relative w-20 h-20 rounded-xl bg-neutral-100 overflow-hidden shrink-0">
                      {item.image ? (
                        <Image src={item.image} alt={item.name} fill className="object-cover" unoptimized />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center text-neutral-300"><Package size={24} /></div>
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <Link href={`/shop/${item.slug}`} className="font-semibold text-navy-800 text-sm hover:underline line-clamp-2">{item.name}</Link>
                      <div className="text-navy-600 font-bold mt-1">${item.price.toFixed(2)}</div>
                    </div>
                    <div className="flex items-center border border-neutral-200 rounded-lg overflow-hidden shrink-0">
                      <button onClick={() => updateQty(key, -1)} className="px-2.5 py-2 hover:bg-neutral-100 text-neutral-500"><Minus size={12} /></button>
                      <span className="px-3 py-2 text-sm font-semibold min-w-[2.5rem] text-center">{item.quantity}</span>
                      <button onClick={() => updateQty(key, 1)} className="px-2.5 py-2 hover:bg-neutral-100 text-neutral-500"><Plus size={12} /></button>
                    </div>
                    <div className="text-sm font-bold text-neutral-800 w-20 text-right shrink-0">
                      ${(item.price * item.quantity).toFixed(2)}
                    </div>
                    <button onClick={() => removeItem(key)} className="p-2 text-neutral-300 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors shrink-0">
                      <Trash2 size={14} />
                    </button>
                  </div>
                );
              })}

              <div className="flex justify-between items-center pt-2">
                <Link href="/shop" className="text-sm text-navy-600 hover:underline font-medium">← Continue Shopping</Link>
                <button onClick={() => persist([])} className="text-xs text-red-400 hover:text-red-600 font-medium">Clear cart</button>
              </div>
            </div>

            {/* Summary */}
            <div className="lg:col-span-1">
              <div className="bg-white rounded-2xl border border-neutral-200 p-6 sticky top-24">
                <h2 className="font-bold text-neutral-800 mb-5">Order Summary</h2>
                <div className="space-y-3 text-sm mb-5">
                  {items.map(item => (
                    <div key={item.productId + (item.variationId ?? "")} className="flex justify-between text-neutral-600">
                      <span className="truncate pr-2">{item.name} ×{item.quantity}</span>
                      <span className="shrink-0 font-medium">${(item.price * item.quantity).toFixed(2)}</span>
                    </div>
                  ))}
                </div>
                <div className="border-t border-neutral-200 pt-4 flex justify-between font-bold text-lg mb-6">
                  <span>Total</span>
                  <span className="text-navy-700">${total.toFixed(2)}</span>
                </div>
                <Link href="/shop/checkout" className="flex items-center justify-center gap-2 w-full py-3.5 bg-navy-700 text-white font-semibold rounded-xl hover:bg-navy-800 transition-colors">
                  Proceed to Checkout <ArrowRight size={16} />
                </Link>
                <p className="text-[11px] text-neutral-400 text-center mt-3">Secure checkout powered by Stripe</p>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
