'use client';
import { useEffect, useState, useCallback } from 'react';

interface CartItem {
  variantId: string;
  productId: string;
  name: string;
  unitPriceCents: number;
  quantity: number;
  imageUrl?: string;
}

interface StockMap {
  [variantId: string]: number;
}

function readCart(): CartItem[] {
  if (typeof window === 'undefined') return [];
  try {
    const raw = localStorage.getItem('mdv_cart');
    if (!raw) return [];
    const data = JSON.parse(raw) as { items?: CartItem[] };
    return data.items ?? [];
  } catch {
    return [];
  }
}

function writeCart(items: CartItem[]): void {
  localStorage.setItem('mdv_cart', JSON.stringify({ items }));
  window.dispatchEvent(new CustomEvent('mdv:cart-updated'));
}

export default function CartPage() {
  const [items, setItems] = useState<CartItem[]>([]);
  const [stock, setStock] = useState<StockMap>({});
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    const data = readCart();
    setItems(data);
    // Fetch stock per variant
    const map: StockMap = {};
    await Promise.all(
      data.map(async (item) => {
        try {
          const res = await fetch(`/api/inventory/${encodeURIComponent(item.variantId)}/availability`);
          if (res.ok) {
            const json = await res.json();
            map[item.variantId] = json.availableQuantity ?? 0;
          } else {
            map[item.variantId] = 0;
          }
        } catch {
          map[item.variantId] = 0;
        }
      }),
    );
    setStock(map);
    setLoading(false);
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const updateQty = async (variantId: string, newQty: number) => {
    const max = stock[variantId] ?? 0;
    if (newQty < 1) return;
    if (newQty > max) {
      setError(`Solo hay ${max} unidades disponibles para esta variante.`);
      return;
    }
    setError('');
    const next = items.map((it) => (it.variantId === variantId ? { ...it, quantity: newQty } : it));
    setItems(next);
    writeCart(next);
    // Sync to backend if logged in
    try {
      await fetch(`/api/cart/items/${encodeURIComponent(variantId)}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ quantity: newQty }),
      });
    } catch {
      // ignore network errors; localStorage remains source of truth
    }
  };

  const remove = (variantId: string) => {
    const next = items.filter((it) => it.variantId !== variantId);
    setItems(next);
    writeCart(next);
    void fetch(`/api/cart/items/${encodeURIComponent(variantId)}`, { method: 'DELETE' }).catch(() => undefined);
  };

  const total = items.reduce((sum, it) => sum + it.unitPriceCents * it.quantity, 0);

  return (
    <div className="mx-auto max-w-4xl px-6 py-12">
      <h1 className="text-3xl font-bold text-emerald-950">Carrito</h1>
      {loading ? (
        <p className="mt-6 text-stone-500">Cargando...</p>
      ) : items.length === 0 ? (
        <p className="mt-6 text-stone-500">Tu carrito está vacío.</p>
      ) : (
        <div className="mt-8 space-y-4">
          {items.map((item) => {
            const max = stock[item.variantId] ?? 0;
            const overStock = item.quantity > max;
            return (
              <div
                key={item.variantId}
                className="flex items-center gap-4 rounded-2xl border border-emerald-900/10 bg-white p-4"
              >
                {item.imageUrl && (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img src={item.imageUrl} alt={item.name} className="h-20 w-20 rounded-lg object-cover" />
                )}
                <div className="flex-1">
                  <p className="font-semibold text-emerald-950">{item.name}</p>
                  <p className="text-sm text-stone-500">{(item.unitPriceCents / 100).toFixed(2)} € / unidad</p>
                  <p className="text-xs text-stone-400">Stock disponible: {max}</p>
                </div>
                <div className="flex items-center gap-2">
                  <input
                    type="number"
                    min={1}
                    max={max}
                    value={item.quantity}
                    onChange={(e) => {
                      const v = parseInt(e.target.value, 10);
                      if (!isNaN(v)) updateQty(item.variantId, v);
                    }}
                    className={`w-20 rounded-lg border px-2 py-1 text-sm focus:ring-2 focus:ring-emerald-700 outline-none ${overStock ? 'border-red-400' : 'border-stone-300'}`}
                  />
                  <button
                    onClick={() => remove(item.variantId)}
                    className="rounded-lg px-3 py-1 text-sm text-stone-500 hover:bg-stone-100"
                  >
                    Quitar
                  </button>
                </div>
              </div>
            );
          })}
          {error && (
            <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-2 text-sm text-red-700">{error}</div>
          )}
          <div className="flex items-center justify-between border-t border-emerald-900/10 pt-4">
            <p className="text-lg font-bold text-emerald-950">Total: {(total / 100).toFixed(2)} €</p>
            <a
              href="/checkout"
              className="rounded-xl bg-emerald-800 px-5 py-2.5 text-sm font-semibold text-white hover:bg-emerald-900"
            >
              Tramitar pedido
            </a>
          </div>
        </div>
      )}
    </div>
  );
}