'use client';
import { useState, useEffect, useCallback } from 'react';
import { productsApi, inventoryApi } from '@/lib/api-client';
import type { Product, ProductVariant, StockAvailability } from '@/types';

interface VariantRow {
  productId: string;
  productName: string;
  variant: ProductVariant;
  stock: StockAvailability | null;
  loading: boolean;
  editing: boolean;
  editValue: string;
  saving: boolean;
  msg: string;
}

type StockFilter = 'all' | 'in_stock' | 'low_stock' | 'out_of_stock';

const STOCK_LABELS: Record<StockFilter, string> = {
  all: 'Todos',
  in_stock: 'En stock',
  low_stock: 'Stock bajo',
  out_of_stock: 'Sin stock',
};

function StockBadge({ qty }: { qty: number }) {
  if (qty === 0) return <span className="px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-700">Sin stock</span>;
  if (qty < 5) return <span className="px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700">Stock bajo ({qty})</span>;
  return <span className="px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700">En stock ({qty})</span>;
}

export default function InventoryPage() {
  const [rows, setRows] = useState<VariantRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [filter, setFilter] = useState<StockFilter>('all');
  const [search, setSearch] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');

  // Debounce search
  useEffect(() => {
    const t = setTimeout(() => setDebouncedSearch(search), 400);
    return () => clearTimeout(t);
  }, [search]);

  // Load products + variants + stock
  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const { items: products } = await productsApi.list({
        limit: 100,
        q: debouncedSearch || undefined,
      });

      const variantRows: VariantRow[] = [];

      for (const product of products ?? []) {
        const { items: variants } = await productsApi.getVariants(product.id);
        for (const variant of variants ?? []) {
          variantRows.push({
            productId: product.id,
            productName: product.name,
            variant,
            stock: null,
            loading: true,
            editing: false,
            editValue: '',
            saving: false,
            msg: '',
          });
        }
      }

      setRows(variantRows);

      // Load stock for each variant
      for (const vr of variantRows) {
        inventoryApi.getAvailability(vr.variant.id)
          .then((stock) => {
            setRows((prev) =>
              prev.map((r) =>
                r.variant.id === vr.variant.id
                  ? { ...r, stock, loading: false, editValue: String(stock.availableQuantity) }
                  : r,
              ),
            );
          })
          .catch(() => {
            setRows((prev) =>
              prev.map((r) =>
                r.variant.id === vr.variant.id ? { ...r, loading: false, editValue: '0' } : r,
              ),
            );
          });
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Error al cargar inventario');
    } finally {
      setLoading(false);
    }
  }, [debouncedSearch]);

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

  // Filter rows
  const filtered = rows.filter((r) => {
    if (filter === 'in_stock') return (r.stock?.availableQuantity ?? 0) >= 5;
    if (filter === 'low_stock') return (r.stock?.availableQuantity ?? 0) > 0 && (r.stock?.availableQuantity ?? 0) < 5;
    if (filter === 'out_of_stock') return (r.stock?.availableQuantity ?? 0) === 0;
    return true;
  });

  const inStockCount = rows.filter((r) => (r.stock?.availableQuantity ?? 0) >= 5).length;
  const lowStockCount = rows.filter((r) => {
    const q = r.stock?.availableQuantity ?? 0;
    return q > 0 && q < 5;
  }).length;
  const outOfStockCount = rows.filter((r) => (r.stock?.availableQuantity ?? 0) === 0).length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Inventario</h1>
          <p className="text-sm text-gray-500 mt-0.5">{rows.length} variantes</p>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-3 gap-4">
        {[
          { label: 'En stock', count: inStockCount, cls: 'bg-green-50 border-green-100 text-green-700' },
          { label: 'Stock bajo', count: lowStockCount, cls: 'bg-amber-50 border-amber-100 text-amber-700' },
          { label: 'Sin stock', count: outOfStockCount, cls: 'bg-red-50 border-red-100 text-red-700' },
        ].map(({ label, count, cls }) => (
          <div key={label} className={`p-4 rounded-xl border ${cls}`}>
            <p className="text-2xl font-bold">{count}</p>
            <p className="text-sm font-medium">{label}</p>
          </div>
        ))}
      </div>

      {/* Search + filters */}
      <div className="flex items-center gap-4">
        <div className="relative flex-1 max-w-sm">
          <input
            type="search"
            placeholder="Buscar por producto o SKU..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] focus:border-transparent outline-none"
          />
          <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <circle cx="11" cy="11" r="8" /><path d="M21 21l-4.35-4.35" />
          </svg>
        </div>

        <div className="flex gap-2">
          {(Object.keys(STOCK_LABELS) as StockFilter[]).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                filter === f
                  ? 'bg-[#2D6A4F] text-white'
                  : 'bg-white border border-gray-300 text-gray-600 hover:bg-gray-50'
              }`}
            >
              {STOCK_LABELS[f]}
            </button>
          ))}
        </div>

        <button
          onClick={load}
          className="text-sm text-[#2D6A4F] hover:underline"
        >
          Recargar
        </button>
      </div>

      {/* Table */}
      <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
        {loading ? (
          <div className="p-12 flex items-center justify-center gap-3 text-gray-400">
            <div className="h-5 w-5 border-2 border-gray-300 border-t-[#2D6A4F] rounded-full animate-spin" />
            <span className="text-sm">Cargando inventario...</span>
          </div>
        ) : error ? (
          <div className="text-center">
            <p className="text-red-600 text-sm mb-3">{error}</p>
            <button onClick={load} className="text-sm text-[#2D6A4F] hover:underline">Reintentar</button>
          </div>
        ) : filtered.length === 0 ? (
          <div className="p-12 text-center">
            <p className="text-4xl mb-3">📦</p>
            <p className="text-gray-500 text-sm">No hay variantes para este filtro</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-200 text-left">
                  <th className="px-4 py-3 font-semibold text-gray-600 text-xs uppercase tracking-wide">Producto</th>
                  <th className="px-4 py-3 font-semibold text-gray-600 text-xs uppercase tracking-wide">SKU</th>
                  <th className="px-4 py-3 font-semibold text-gray-600 text-xs uppercase tracking-wide">EAN</th>
                  <th className="px-4 py-3 font-semibold text-gray-600 text-xs uppercase tracking-wide">Stock</th>
                  <th className="px-4 py-3 font-semibold text-gray-600 text-xs uppercase tracking-wide">Estado</th>
                  <th className="px-4 py-3 font-semibold text-gray-600 text-xs uppercase tracking-wide">Acción</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {filtered.map((row) => (
                  <tr key={row.variant.id} className="hover:bg-gray-50/50 transition-colors">
                    <td className="px-4 py-3">
                      <p className="text-sm font-medium text-gray-900">{row.productName}</p>
                    </td>
                    <td className="px-4 py-3 font-mono text-xs text-gray-600">{row.variant.sku}</td>
                    <td className="px-4 py-3 font-mono text-xs text-gray-400">{row.variant.ean ?? '—'}</td>
                    <td className="px-4 py-3">
                      {row.loading ? (
                        <span className="text-gray-300">—</span>
                      ) : row.editing ? (
                        <div className="flex items-center gap-1">
                          <input
                            type="number"
                            min={0}
                            value={row.editValue}
                            onChange={(e) =>
                              setRows((prev) =>
                                prev.map((r) =>
                                  r.variant.id === row.variant.id
                                    ? { ...r, editValue: e.target.value }
                                    : r,
                                ),
                              )
                            }
                            className="w-20 px-2 py-1 border border-gray-300 rounded-lg text-sm focus:ring-1 focus:ring-[#2D6A4F] outline-none"
                          />
                          <button
                            onClick={async () => {
                              const qty = parseInt(row.editValue, 10);
                              if (isNaN(qty) || qty < 0) return;
                              setRows((prev) =>
                                prev.map((r) =>
                                  r.variant.id === row.variant.id ? { ...r, saving: true } : r,
                                ),
                              );
                              try {
                                const result = await inventoryApi.setStock(row.variant.id, qty);
                                setRows((prev) =>
                                  prev.map((r) =>
                                    r.variant.id === row.variant.id
                                      ? {
                                          ...r,
                                          stock: { available: result.available > 0, availableQuantity: result.available },
                                          editing: false,
                                          saving: false,
                                          msg: '✓',
                                        }
                                      : r,
                                  ),
                                );
                                setTimeout(() => {
                                  setRows((prev) =>
                                    prev.map((r) =>
                                      r.variant.id === row.variant.id ? { ...r, msg: '' } : r,
                                    ),
                                  );
                                }, 3000);
                              } catch {
                                setRows((prev) =>
                                  prev.map((r) =>
                                    r.variant.id === row.variant.id
                                      ? { ...r, saving: false, msg: 'Error' }
                                      : r,
                                  ),
                                );
                              }
                            }}
                            disabled={row.saving}
                            className="px-2 py-1 bg-[#2D6A4F] text-white text-xs rounded-lg hover:bg-[#1B4332] disabled:opacity-50"
                          >
                            {row.saving ? '...' : 'OK'}
                          </button>
                          <button
                            onClick={() =>
                              setRows((prev) =>
                                prev.map((r) =>
                                  r.variant.id === row.variant.id
                                    ? {
                                        ...r,
                                        editing: false,
                                        editValue: String(r.stock?.availableQuantity ?? 0),
                                      }
                                    : r,
                                ),
                              )
                            }
                            className="text-gray-400 hover:text-gray-600 text-xs"
                          >
                            ✕
                          </button>
                        </div>
                      ) : (
                        <div className="flex items-center gap-1">
                          <span className="font-medium text-gray-900">
                            {row.stock?.availableQuantity ?? '—'}
                          </span>
                          <button
                            onClick={() =>
                              setRows((prev) =>
                                prev.map((r) =>
                                  r.variant.id === row.variant.id ? { ...r, editing: true } : r,
                                ),
                              )
                            }
                            className="ml-1 text-gray-400 hover:text-[#2D6A4F] text-xs"
                            title="Editar stock"
                          >
                            ✏️
                          </button>
                        </div>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <StockBadge qty={row.stock?.availableQuantity ?? 0} />
                    </td>
                    <td className="px-4 py-3">
                      {row.msg && (
                        <span className={`text-xs ${row.msg === '✓' ? 'text-green-600' : 'text-red-600'}`}>
                          {row.msg}
                        </span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
