import type { FC } from 'react';
import { useEffect, useState, useCallback, useMemo } from 'react';
import { Boxes } from 'lucide-react';
import { Card, Badge, EmptyState, Skeleton, toast } from '../ui';
import { ExportButton } from '../ui/ExportButton';
import { exportToExcel } from '../../lib/exporter';
import { odooApi, type InventoryItem, type InventoryReportSummary } from '../../services/odoo';
import type { BadgeVariant } from '../ui/Badge';

const formatCurrency = (value: number) =>
  new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN', maximumFractionDigits: 0 }).format(value);

const levelBadge = (level: string): BadgeVariant => {
  switch (level) {
    case 'out': return 'danger';
    case 'critical': case 'low': return 'warning';
    default: return 'success';
  }
};

const levelLabels: Record<string, string> = {
  out: 'Sin existencias', critical: 'Crítico', low: 'Bajo', optimal: 'Óptimo',
};

const FILTROS = [
  { key: 'todos', label: 'Todos' },
  { key: 'bajo', label: 'Bajo mínimo' },
  { key: 'out', label: 'Sin existencias' },
] as const;

const InventarioReport: FC = () => {
  const [items, setItems] = useState<InventoryItem[]>([]);
  const [summary, setSummary] = useState<InventoryReportSummary | null>(null);
  const [loading, setLoading] = useState(true);
  const [filtro, setFiltro] = useState<string>('todos');

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getInventoryReport();
      if (res.status === 'success') {
        setItems(res.items);
        setSummary(res.summary);
      }
    } catch (err) {
      toast.error('Error al cargar reporte de inventario');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const visibles = useMemo(() => {
    if (filtro === 'out') return items.filter((i) => i.stock_level === 'out');
    if (filtro === 'bajo') return items.filter((i) => i.stock_level === 'critical' || i.stock_level === 'low');
    return items;
  }, [items, filtro]);

  const [exporting, setExporting] = useState(false);
  const exportar = async () => {
    try {
      setExporting(true);
      const filtroLabel = FILTROS.find((f) => f.key === filtro)?.label || 'Todos';
      await exportToExcel({
        filename: `inventario-${filtro}-${new Date().toISOString().split('T')[0]}`,
        sheetName: 'Inventario',
        title: 'Reporte de inventario',
        subtitle: `Filtro: ${filtroLabel} · ${visibles.length} artículos · valor total ${formatCurrency(summary?.total_value ?? 0)}`,
        columns: [
          { header: 'Artículo', key: 'name' },
          { header: 'Categoría', key: 'category' },
          { header: 'Unidad', key: 'unit' },
          { header: 'Existencia', key: 'qty', format: 'number' },
          { header: 'Mínimo', key: 'qty_min', format: 'number' },
          { header: 'Óptimo', key: 'qty_optimal', format: 'number' },
          { header: 'Costo', key: 'cost', format: 'currency' },
          { header: 'Valor', key: 'inventory_value', format: 'currency' },
          { header: 'Nivel', key: 'nivel' },
        ],
        rows: visibles.map((i) => ({ ...i, nivel: levelLabels[i.stock_level] || i.stock_level })),
        totals: { name: '', inventory_value: visibles.reduce((a, i) => a + i.inventory_value, 0) },
      });
      toast.success('Excel descargado');
    } catch (err) {
      toast.error('Error al exportar');
      console.error(err);
    } finally {
      setExporting(false);
    }
  };

  return (
    <div className="space-y-4 sm:space-y-6">
      {loading ? (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-24 w-full" />)}
        </div>
      ) : summary ? (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <Card className="p-4 bg-theme-bg border-0">
            <p className="text-xs text-theme-muted">Valor del inventario</p>
            <p className="text-xl font-heading font-semibold text-theme-heading">{formatCurrency(summary.total_value)}</p>
          </Card>
          <Card className="p-4 bg-theme-bg border-0">
            <p className="text-xs text-theme-muted">Artículos</p>
            <p className="text-xl font-heading font-semibold text-theme-heading">{summary.count}</p>
          </Card>
          <Card className="p-4 bg-theme-bg border-0">
            <p className="text-xs text-theme-muted">Sin existencias</p>
            <p className={`text-xl font-heading font-semibold ${summary.out > 0 ? 'text-rose-600' : 'text-theme-heading'}`}>{summary.out}</p>
          </Card>
          <Card className="p-4 bg-theme-bg border-0">
            <p className="text-xs text-theme-muted">Bajo mínimo</p>
            <p className="text-xl font-heading font-semibold text-theme-heading">{summary.critical}</p>
          </Card>
        </div>
      ) : null}

      <Card>
        <Card.Body>
          <div className="flex flex-wrap items-center gap-1.5 mb-4">
            {FILTROS.map((f) => (
              <button
                key={f.key}
                type="button"
                onClick={() => setFiltro(f.key)}
                className={`px-3 py-1.5 text-sm font-medium rounded-full transition ${
                  filtro === f.key ? 'bg-theme-accent text-theme-inverse' : 'bg-theme-accent-bg text-theme-heading hover:bg-theme-bg'
                }`}
              >
                {f.label}
              </button>
            ))}
            <div className="ml-auto">
              <ExportButton onClick={exportar} loading={exporting} />
            </div>
          </div>

          {loading ? (
            <Skeleton count={8} className="h-10 w-full" />
          ) : visibles.length === 0 ? (
            <EmptyState title="Sin artículos" subtitle="No hay artículos con este filtro." icon={<Boxes size={28} />} />
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-theme-bg text-theme-muted text-xs uppercase">
                  <tr>
                    <th className="text-left px-4 py-3">Artículo</th>
                    <th className="text-left px-4 py-3 hidden md:table-cell">Categoría</th>
                    <th className="text-left px-4 py-3 hidden sm:table-cell">Unidad</th>
                    <th className="text-right px-4 py-3">Existencia</th>
                    <th className="text-right px-4 py-3 hidden sm:table-cell">Mínimo</th>
                    <th className="text-right px-4 py-3 hidden md:table-cell">Óptimo</th>
                    <th className="text-right px-4 py-3 hidden sm:table-cell">Costo</th>
                    <th className="text-right px-4 py-3">Valor</th>
                    <th className="text-left px-4 py-3">Nivel</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-theme-border">
                  {visibles.map((i) => (
                    <tr key={i.id} className="hover:bg-theme-bg">
                      <td className="px-4 py-3 font-medium text-theme-heading">{i.name}</td>
                      <td className="px-4 py-3 text-theme-muted hidden md:table-cell">{i.category || '-'}</td>
                      <td className="px-4 py-3 text-theme-muted hidden sm:table-cell">{i.unit}</td>
                      <td className="px-4 py-3 text-right text-theme-heading">{i.qty}</td>
                      <td className="px-4 py-3 text-right text-theme-muted hidden sm:table-cell">{i.qty_min || '-'}</td>
                      <td className="px-4 py-3 text-right text-theme-muted hidden md:table-cell">{i.qty_optimal || '-'}</td>
                      <td className="px-4 py-3 text-right text-theme-muted hidden sm:table-cell">{formatCurrency(i.cost)}</td>
                      <td className="px-4 py-3 text-right font-medium text-theme-heading">{formatCurrency(i.inventory_value)}</td>
                      <td className="px-4 py-3">
                        <Badge variant={levelBadge(i.stock_level)}>{levelLabels[i.stock_level] || i.stock_level}</Badge>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </Card.Body>
      </Card>
    </div>
  );
};

export default InventarioReport;
