import type { FC } from 'react';
import { useEffect, useState } from 'react';
import { Package, Search } from 'lucide-react';
import Layout from '../components/Layout';
import { Card, Input, Badge, EmptyState, PageHeader, Skeleton, MobileCard, toast } from '../components/ui';
import { odooApi, type Product } from '../services/odoo';

const translateType = (type: string) => {
  const map: Record<string, string> = {
    product: 'Producto almacenable',
    service: 'Servicio',
    consu: 'Consumible',
  };
  return map[type] || type;
};

const Productos: FC = () => {
  const [products, setProducts] = useState<Product[]>([]);
  const [filtered, setFiltered] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState('');

  useEffect(() => {
    const load = async () => {
      try {
        setLoading(true);
        setError(null);
        const res = await odooApi.getProducts();
        if (res.status === 'success') {
          setProducts(res.products);
          setFiltered(res.products);
        }
      } catch (err) {
        setError('Error al cargar productos');
        toast.error('Error al cargar productos');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };
    load();
  }, []);

  useEffect(() => {
    const term = search.toLowerCase();
    setFiltered(
      products.filter(
        (p) =>
          p.name.toLowerCase().includes(term) ||
          (p.default_code && p.default_code.toLowerCase().includes(term)) ||
          p.type.toLowerCase().includes(term)
      )
    );
  }, [search, products]);

  return (
    <Layout title="Productos" subtitle="Inventario">
      <PageHeader title="Productos" subtitle="Catálogo de productos" />

      <Card>
        <Card.Body>
          <div className="flex flex-col sm:flex-row sm:items-center gap-3 mb-4 sm:mb-6">
            <div className="relative w-full sm:max-w-sm">
              <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-[#A87B5D]" />
              <Input
                placeholder="Buscar por nombre, código o tipo..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>

          {error && <p className="text-rose-600 text-sm mb-4">{error}</p>}

          {loading ? (
            <Skeleton count={6} className="h-12 w-full" />
          ) : filtered.length === 0 ? (
            <EmptyState title="Sin productos" subtitle="No se encontraron productos." icon={<Package size={28} />} />
          ) : (
            <>
              <div className="hidden sm:block overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-[#FEF3C7]">
                    <tr>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Referencia</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Nombre</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Tipo</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Precio</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {filtered.map((p) => (
                      <tr key={p.id} className="hover:bg-[#FEF3C7]">
                        <td className="p-3 text-sm text-[#7A5C44]">{p.default_code || '-'}</td>
                        <td className="p-3 text-sm font-medium text-homenest-bark">{p.name}</td>
                        <td className="p-3">
                          <Badge variant="default">{translateType(p.type)}</Badge>
                        </td>
                        <td className="p-3 text-sm font-semibold text-homenest-bark">${p.list_price}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div className="sm:hidden space-y-3">
                {filtered.map((p) => (
                  <MobileCard
                    key={p.id}
                    title={p.name}
                    subtitle={<Badge variant="default">{translateType(p.type)}</Badge>}
                    rows={[
                      { label: 'Referencia', value: p.default_code || '-' },
                      { label: 'Precio', value: `$${p.list_price}` },
                    ]}
                  />
                ))}
              </div>
            </>
          )}
        </Card.Body>
      </Card>
    </Layout>
  );
};

export default Productos;
