import type { FC } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { Plus, Search } from 'lucide-react';
import {
  Card,
  Button,
  Input,
  Select,
  Modal,
  EmptyState,
  Skeleton,
  toast,
} from '../ui';
import { odooApi, type MovimientoRow, type InventoryItem } from '../../services/odoo';

const fmtMoney = (n: number) =>
  (n || 0).toLocaleString('es-MX', { style: 'currency', currency: 'MXN', maximumFractionDigits: 0 });

interface MovimientosPanelProps {
  tipo: 'compra' | 'baja';
}

const MovimientosPanel: FC<MovimientosPanelProps> = ({ tipo }) => {
  const esCompra = tipo === 'compra';
  const [movimientos, setMovimientos] = useState<MovimientoRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);
  const [total, setTotal] = useState(0);

  const [modalOpen, setModalOpen] = useState(false);
  const [items, setItems] = useState<InventoryItem[]>([]);
  const [itemSearch, setItemSearch] = useState('');
  const [form, setForm] = useState({ item_id: '', qty: '1', cost: '', reference: '', notes: '' });
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const params: Record<string, string | number> = { type: tipo, page, page_size: 50 };
      if (search) params.search = search;
      const res = await odooApi.getMovimientos(params);
      if (res.status === 'success') {
        setMovimientos(res.movimientos);
        setTotal(res.total ?? 0);
        setTotalPages(res.total_pages ?? 0);
      }
    } catch (err) {
      toast.error('Error al cargar movimientos');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [tipo, search, page]);

  useEffect(() => { setPage(1); }, [search, tipo]);
  useEffect(() => { load(); }, [load]);

  // Catálogo de artículos para el select del modal
  useEffect(() => {
    if (!modalOpen) return;
    odooApi.getInventarioItems(itemSearch || undefined)
      .then((res) => { if (res.status === 'success') setItems(res.items); })
      .catch(() => {});
  }, [modalOpen, itemSearch]);

  const openModal = () => {
    setForm({ item_id: '', qty: '1', cost: '', reference: '', notes: '' });
    setItemSearch('');
    setModalOpen(true);
  };

  const guardar = async () => {
    const qty = parseFloat(form.qty);
    if (!form.item_id) {
      toast.error('Selecciona un artículo');
      return;
    }
    if (Number.isNaN(qty) || qty <= 0) {
      toast.error('La cantidad debe ser mayor a 0');
      return;
    }
    try {
      setSaving(true);
      const payload = {
        item_id: parseInt(form.item_id, 10),
        qty,
        reference: form.reference,
        notes: form.notes,
        ...(esCompra && form.cost !== '' ? { cost: parseFloat(form.cost) } : {}),
      };
      const res = esCompra ? await odooApi.createCompra(payload) : await odooApi.createBaja(payload);
      if (res.status === 'success') {
        toast.success(esCompra ? 'Compra registrada' : 'Baja registrada');
        setModalOpen(false);
        await load();
      }
    } catch (err) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      toast.error(msg || 'Error al registrar el movimiento');
      console.error(err);
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <Card className="mb-4">
        <Card.Body>
          <div className="flex flex-col sm:flex-row sm:items-center gap-3">
            <div className="relative flex-1 sm:max-w-sm">
              <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-theme-muted" />
              <Input
                placeholder="Buscar por artículo..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="pl-10"
              />
            </div>
            <Button onClick={openModal} className="sm:ml-auto">
              <Plus size={16} className="mr-2" />
              {esCompra ? 'Registrar compra' : 'Registrar baja'}
            </Button>
          </div>
        </Card.Body>
      </Card>

      <Card>
        <Card.Body>
          {loading ? (
            <Skeleton count={8} className="h-10 w-full" />
          ) : movimientos.length === 0 ? (
            <EmptyState
              title={esCompra ? 'Sin compras' : 'Sin bajas'}
              subtitle={esCompra ? 'No hay compras registradas.' : 'No hay bajas/mermas registradas.'}
              actionLabel={esCompra ? 'Registrar compra' : 'Registrar baja'}
              onAction={openModal}
            />
          ) : (
            <>
              <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">Fecha</th>
                      <th className="text-left px-4 py-3">Artículo</th>
                      <th className="text-right px-4 py-3">Cantidad</th>
                      <th className="text-right px-4 py-3 hidden sm:table-cell">Antes</th>
                      <th className="text-right px-4 py-3 hidden sm:table-cell">Después</th>
                      <th className="text-left px-4 py-3 hidden md:table-cell">{esCompra ? 'Referencia' : 'Motivo / Referencia'}</th>
                      <th className="text-left px-4 py-3 hidden md:table-cell">Notas</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-theme-border">
                    {movimientos.map((m) => (
                      <tr key={m.id} className="hover:bg-theme-bg">
                        <td className="px-4 py-3 text-theme-muted whitespace-nowrap">{m.date || '-'}</td>
                        <td className="px-4 py-3 font-medium text-theme-heading">{m.item}</td>
                        <td className={`px-4 py-3 text-right font-medium ${esCompra ? 'text-theme-heading' : 'text-rose-600'}`}>
                          {esCompra ? '+' : '−'}{m.qty} {m.unit}
                        </td>
                        <td className="px-4 py-3 text-right text-theme-muted hidden sm:table-cell">{m.before_qty}</td>
                        <td className="px-4 py-3 text-right text-theme-muted hidden sm:table-cell">{m.after_qty}</td>
                        <td className="px-4 py-3 text-theme-muted hidden md:table-cell">{m.reference || '-'}</td>
                        <td className="px-4 py-3 text-theme-muted hidden md:table-cell">
                          <span className="block max-w-[200px] truncate">{m.notes || '-'}</span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <div className="flex items-center justify-between mt-4 pt-4 border-t border-theme-border">
                <p className="text-sm text-theme-muted">{total} movimientos · página {page} de {totalPages || 1}</p>
                <div className="flex items-center gap-2">
                  <Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => Math.max(1, p - 1))}>Anterior</Button>
                  <Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>Siguiente</Button>
                </div>
              </div>
            </>
          )}
        </Card.Body>
      </Card>

      {/* Modal registrar movimiento */}
      <Modal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        title={esCompra ? 'Registrar compra' : 'Registrar baja / merma'}
        maxWidth="md"
        footer={
          <>
            <Button variant="outline" onClick={() => setModalOpen(false)}>Cancelar</Button>
            <Button onClick={guardar} loading={saving}>{esCompra ? 'Registrar compra' : 'Registrar baja'}</Button>
          </>
        }
      >
        <div className="space-y-4">
          <Input
            placeholder="Buscar artículo..."
            value={itemSearch}
            onChange={(e) => setItemSearch(e.target.value)}
          />
          <Select
            label="Artículo *"
            options={[
              { value: '', label: 'Selecciona artículo...' },
              ...items.map((i) => ({ value: String(i.id), label: `${i.name} (${i.qty} ${i.unit})` })),
            ]}
            value={form.item_id}
            onChange={(e) => setForm({ ...form, item_id: e.target.value })}
          />
          <Input
            label="Cantidad *"
            type="number"
            min="0.5"
            step="0.5"
            value={form.qty}
            onChange={(e) => setForm({ ...form, qty: e.target.value })}
          />
          {esCompra && (
            <Input
              label="Costo unitario (actualiza el costo del artículo)"
              type="number"
              min="0"
              step="0.01"
              value={form.cost}
              onChange={(e) => setForm({ ...form, cost: e.target.value })}
              placeholder="Opcional"
            />
          )}
          <Input
            label={esCompra ? 'Referencia (proveedor / factura)' : 'Referencia'}
            value={form.reference}
            onChange={(e) => setForm({ ...form, reference: e.target.value })}
          />
          <Input
            label={esCompra ? 'Notas' : 'Motivo'}
            value={form.notes}
            onChange={(e) => setForm({ ...form, notes: e.target.value })}
          />
          {esCompra && form.cost !== '' && (
            <p className="text-xs text-theme-muted">
              Costo total estimado: {fmtMoney((parseFloat(form.qty) || 0) * (parseFloat(form.cost) || 0))}
            </p>
          )}
        </div>
      </Modal>
    </>
  );
};

export default MovimientosPanel;
