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

interface Props {
  productId: string;
  productName: string;
  unitPriceCents: number;
  imageUrl?: string;
}

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

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 function AddToCart({ productId, productName, unitPriceCents, imageUrl }: Props) {
  const [stock, setStock] = useState<number>(0);
  const [qty, setQty] = useState<number>(1);
  const [error, setError] = useState<string>('');
  const [added, setAdded] = useState<boolean>(false);

  useEffect(() => {
    fetch(`/api/inventory/${encodeURIComponent(productId)}/availability`)
      .then(async (r) => (r.ok ? await r.json() : { availableQuantity: 0 }))
      .then((j) => setStock(j.availableQuantity ?? 0))
      .catch(() => setStock(0));
  }, [productId]);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    if (qty < 1) {
      setError('La cantidad debe ser al menos 1.');
      return;
    }
    if (qty > stock) {
      setError(`Solo hay ${stock} unidades disponibles.`);
      return;
    }
    const items = readCart();
    const existing = items.find((it) => it.variantId === productId);
    const newQty = existing ? existing.quantity + qty : qty;
    if (newQty > stock) {
      setError(`Solo hay ${stock} unidades disponibles.`);
      return;
    }
    const next = existing
      ? items.map((it) => (it.variantId === productId ? { ...it, quantity: newQty } : it))
      : [
          ...items,
          { variantId: productId, productId, name: productName, unitPriceCents, quantity: qty, imageUrl },
        ];
    writeCart(next);
    // Backend sync (best-effort)
    void fetch('/api/cart/items', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ variantId: productId, quantity: qty }),
    }).catch(() => undefined);
    setAdded(true);
    setTimeout(() => setAdded(false), 2500);
  };

  const disabled = stock === 0;

  return (
    <form onSubmit={submit} className="mt-6 space-y-3">
      <div className="flex items-center gap-3">
        <label className="text-sm font-medium text-stone-700">Cantidad</label>
        <input
          type="number"
          min={1}
          max={stock}
          value={qty}
          onChange={(e) => setQty(Math.max(1, parseInt(e.target.value, 10) || 1))}
          disabled={disabled}
          className="w-24 rounded-lg border border-stone-300 px-3 py-2 text-sm focus:ring-2 focus:ring-emerald-700 outline-none disabled:opacity-50"
        />
        <span className="text-xs text-stone-500">Stock: {stock}</span>
      </div>
      {error && <p className="text-sm text-red-600">{error}</p>}
      {added && !error && (
        <p className="text-sm text-emerald-700">✓ Añadido al carrito</p>
      )}
      <button
        type="submit"
        disabled={disabled}
        className="rounded-xl bg-emerald-800 px-5 py-2.5 text-sm font-semibold text-white hover:bg-emerald-900 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {disabled ? 'Sin stock' : 'Añadir al carrito'}
      </button>
    </form>
  );
}