// Module: Stock e insumos

function StockModule() {
  const { state, dispatch } = useStore();
  const toast = useToast();
  const [filter, setFilter] = useState('all');
  const [q, setQ] = useState('');
  const [sortBy, setSortBy] = useState('pct');
  const [adding, setAdding] = useState(false);
  const [moveItem, setMoveItem] = useState(null); // {id, direction}

  const categories = ['all', ...Array.from(new Set(state.stock.map((i) => i.category)))];
  const items = useMemo(() => {
    let list = state.stock.filter((i) => {
      if (filter === 'low') return i.qty < i.min;
      if (filter !== 'all' && filter !== 'low') return i.category === filter;
      return true;
    });
    if (q) list = list.filter((i) => i.name.toLowerCase().includes(q.toLowerCase()));
    list = [...list].sort((a, b) => {
      if (sortBy === 'pct') return a.qty / a.min - b.qty / b.min;
      if (sortBy === 'name') return a.name.localeCompare(b.name);
      if (sortBy === 'qty') return b.qty - a.qty;
      return 0;
    });
    return list;
  }, [state.stock, filter, q, sortBy]);

  const lowCount = state.stock.filter((i) => i.qty < i.min).length;
  const totalItems = state.stock.reduce((s, i) => s + i.qty, 0);

  function adjust(item, delta) {
    dispatch({ type: 'stock/adjust', id: item.id, delta });
    toast({
      title: delta > 0 ? 'Ingreso registrado' : 'Egreso registrado',
      description: `${item.name}: ${delta > 0 ? '+' : ''}${delta} ${item.unit}`,
      variant: delta > 0 ? 'success' : 'default',
    });
  }

  function removeItem(item) {
    dispatch({ type: 'stock/remove', id: item.id });
    toast({ title: 'Ítem eliminado', description: item.name, variant: 'error' });
  }

  return (
    <div className="view-in space-y-5">
      {/* KPIs */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardContent className="pt-5">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
              Ítems totales
            </div>
            <div className="text-[26px] font-bold tracking-tight tnum mt-2">
              {state.stock.length}
            </div>
            <div className="text-[11px] text-muted mt-1">{categories.length - 1} categorías</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
              Unidades en depósito
            </div>
            <div className="text-[26px] font-bold tracking-tight tnum mt-2">
              {totalItems.toLocaleString('es-AR')}
            </div>
            <div className="text-[11px] text-muted mt-1">suma total</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
              Stock bajo
            </div>
            <div
              className={cn(
                'text-[26px] font-bold tracking-tight tnum mt-2',
                lowCount > 0 && 'text-red',
              )}
            >
              {lowCount}
            </div>
            <div className="text-[11px] text-muted mt-1">ítems por debajo del mínimo</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
              Último movimiento
            </div>
            <div className="text-[16px] font-semibold tracking-tight mt-2">Hoy</div>
            <div className="text-[11px] text-muted mt-1">Input manual del operador</div>
          </CardContent>
        </Card>
      </div>

      {/* Controls */}
      <Card>
        <div className="px-5 py-3 border-b border-border flex flex-wrap items-center gap-3">
          <div className="relative">
            <Icon
              name="search"
              size={14}
              className="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400"
            />
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder="Buscar ítem…"
              className="h-9 pl-8 pr-3 w-56 rounded-md border border-border text-[12.5px] focus:outline-none focus:ring-2 focus:ring-amber/30 focus:border-amber"
            />
          </div>
          <Tabs
            value={filter}
            onChange={setFilter}
            options={[
              { value: 'all', label: 'Todos' },
              { value: 'low', label: `Bajo stock · ${lowCount}` },
              { value: 'Barras', label: 'Barras' },
              { value: 'Químico', label: 'Químicos' },
              { value: 'Consumible', label: 'Consumibles' },
              { value: 'Repuesto', label: 'Repuestos' },
            ]}
          />
          <div className="ml-auto flex items-center gap-2">
            <Select value={sortBy} onChange={(e) => setSortBy(e.target.value)} className="w-40">
              <option value="pct">Menor cobertura</option>
              <option value="name">Nombre A-Z</option>
              <option value="qty">Cantidad ↓</option>
            </Select>
            <Button variant="primary" size="sm" onClick={() => setAdding(true)}>
              <Icon name="plus" size={13} /> Nuevo ítem
            </Button>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-[13px]">
            <thead>
              <tr className="bg-slate-50 text-[10.5px] font-semibold text-muted uppercase tracking-wider">
                <th className="text-left px-5 py-2.5">Ítem</th>
                <th className="text-left px-3 py-2.5">Categoría</th>
                <th className="text-right px-3 py-2.5">Cantidad</th>
                <th className="text-right px-3 py-2.5">Mínimo</th>
                <th className="px-3 py-2.5 w-48">Cobertura</th>
                <th className="text-right px-3 py-2.5">Últ. mov.</th>
                <th className="text-right px-5 py-2.5">Acciones</th>
              </tr>
            </thead>
            <tbody>
              {items.map((it) => {
                const pct = Math.min(100, (it.qty / Math.max(1, it.min)) * 50); // 50% means exactly at minimum
                const status = it.qty < it.min ? 'low' : it.qty < it.min * 1.5 ? 'warn' : 'ok';
                return (
                  <tr key={it.id} className="border-t border-border hover:bg-slate-50/60">
                    <td className="px-5 py-3">
                      <div className="font-medium text-ink">{it.name}</div>
                    </td>
                    <td className="px-3 py-3">
                      <Badge variant="outline">{it.category}</Badge>
                    </td>
                    <td className="px-3 py-3 text-right tnum font-semibold">
                      {it.qty.toLocaleString('es-AR')}{' '}
                      <span className="text-[11px] text-muted font-normal">{it.unit}</span>
                    </td>
                    <td className="px-3 py-3 text-right tnum text-muted">
                      {it.min.toLocaleString('es-AR')} {it.unit}
                    </td>
                    <td className="px-3 py-3">
                      <div className="flex items-center gap-2">
                        <div className="flex-1 h-1.5 rounded-full bg-slate-100 overflow-hidden">
                          <div
                            className={cn(
                              'h-full rounded-full',
                              status === 'low'
                                ? 'bg-red'
                                : status === 'warn'
                                  ? 'bg-amber'
                                  : 'bg-emerald',
                            )}
                            style={{ width: `${Math.min(100, pct * 2)}%` }}
                          />
                        </div>
                        <span
                          className={cn(
                            'text-[10.5px] font-semibold tnum min-w-14 text-right',
                            status === 'low'
                              ? 'text-red'
                              : status === 'warn'
                                ? 'text-amber-ink'
                                : 'text-emerald',
                          )}
                        >
                          {status === 'low' ? 'Bajo' : status === 'warn' ? 'Alerta' : 'OK'}
                        </span>
                      </div>
                    </td>
                    <td className="px-3 py-3 text-right tnum text-muted text-[11.5px]">
                      {it.lastMove}
                    </td>
                    <td className="px-5 py-3 text-right">
                      <div className="inline-flex items-center gap-1">
                        <button
                          onClick={() => adjust(it, -1)}
                          className="h-7 w-7 rounded-md border border-border bg-white hover:bg-slate-50 flex items-center justify-center text-muted hover:text-ink"
                          title="Egreso -1"
                        >
                          <Icon name="minus" size={12} />
                        </button>
                        <button
                          onClick={() => adjust(it, 1)}
                          className="h-7 w-7 rounded-md border border-border bg-white hover:bg-slate-50 flex items-center justify-center text-muted hover:text-ink"
                          title="Ingreso +1"
                        >
                          <Icon name="plus" size={12} />
                        </button>
                        <button
                          onClick={() => setMoveItem(it)}
                          className="h-7 px-2 rounded-md border border-border bg-white hover:bg-slate-50 text-[11px] text-muted hover:text-ink"
                        >
                          Mover
                        </button>
                        <button
                          onClick={() => removeItem(it)}
                          className="h-7 w-7 rounded-md border border-border bg-white hover:bg-red-50 hover:border-red/40 flex items-center justify-center text-muted hover:text-red"
                          title="Eliminar"
                        >
                          <Icon name="trash" size={12} />
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {items.length === 0 && (
                <tr>
                  <td colSpan="7" className="px-5 py-10 text-center text-sm text-muted">
                    Sin ítems que coincidan con el filtro.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </Card>

      {/* Add item dialog */}
      <AddStockDialog
        open={adding}
        onClose={() => setAdding(false)}
        onSave={(item) => {
          dispatch({ type: 'stock/add', item });
          toast({ title: 'Ítem agregado', description: item.name, variant: 'success' });
          setAdding(false);
        }}
      />
      <MoveStockDialog
        item={moveItem}
        onClose={() => setMoveItem(null)}
        onSave={(delta) => {
          dispatch({ type: 'stock/adjust', id: moveItem.id, delta });
          toast({
            title: delta > 0 ? 'Ingreso registrado' : 'Egreso registrado',
            description: `${moveItem.name}: ${delta > 0 ? '+' : ''}${delta} ${moveItem.unit}`,
            variant: delta > 0 ? 'success' : 'default',
          });
          setMoveItem(null);
        }}
      />
    </div>
  );
}

function AddStockDialog({ open, onClose, onSave }) {
  const [form, setForm] = useState({ name: '', category: 'Consumible', qty: 0, min: 0, unit: 'u' });
  useEffect(() => {
    if (open) setForm({ name: '', category: 'Consumible', qty: 0, min: 0, unit: 'u' });
  }, [open]);
  const valid = form.name.trim().length > 1;
  return (
    <Dialog
      open={open}
      onClose={onClose}
      title="Nuevo ítem"
      description="Registrar un nuevo material, repuesto o producto químico."
      footer={
        <>
          <Button variant="outline" size="sm" onClick={onClose}>
            Cancelar
          </Button>
          <Button variant="primary" size="sm" disabled={!valid} onClick={() => onSave(form)}>
            Guardar ítem
          </Button>
        </>
      }
    >
      <div className="grid grid-cols-2 gap-4">
        <div className="col-span-2">
          <Label>Nombre</Label>
          <Input
            value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })}
            placeholder="Ej: Barras NQ"
          />
        </div>
        <div>
          <Label>Categoría</Label>
          <Select
            value={form.category}
            onChange={(e) => setForm({ ...form, category: e.target.value })}
          >
            <option>Barras</option>
            <option>Revestimiento</option>
            <option>Consumible</option>
            <option>Repuesto</option>
            <option>Químico</option>
          </Select>
        </div>
        <div>
          <Label>Unidad</Label>
          <Select value={form.unit} onChange={(e) => setForm({ ...form, unit: e.target.value })}>
            <option>u</option>
            <option>kg</option>
            <option>L</option>
            <option>m</option>
          </Select>
        </div>
        <div>
          <Label>Cantidad inicial</Label>
          <Input
            type="number"
            value={form.qty}
            onChange={(e) => setForm({ ...form, qty: Number(e.target.value) })}
          />
        </div>
        <div>
          <Label>Mínimo (alerta)</Label>
          <Input
            type="number"
            value={form.min}
            onChange={(e) => setForm({ ...form, min: Number(e.target.value) })}
          />
        </div>
      </div>
    </Dialog>
  );
}

function MoveStockDialog({ item, onClose, onSave }) {
  const [direction, setDirection] = useState('in');
  const [qty, setQty] = useState(1);
  const [reason, setReason] = useState('');
  useEffect(() => {
    if (item) {
      setDirection('in');
      setQty(1);
      setReason('');
    }
  }, [item]);
  if (!item) return null;
  return (
    <Dialog
      open={true}
      onClose={onClose}
      title={`Mover · ${item.name}`}
      description={`Stock actual: ${item.qty} ${item.unit}`}
      footer={
        <>
          <Button variant="outline" size="sm" onClick={onClose}>
            Cancelar
          </Button>
          <Button
            variant="primary"
            size="sm"
            onClick={() => onSave(direction === 'in' ? qty : -qty)}
          >
            Registrar movimiento
          </Button>
        </>
      }
    >
      <div className="space-y-4">
        <div>
          <Label>Tipo</Label>
          <div className="grid grid-cols-2 gap-2">
            <button
              onClick={() => setDirection('in')}
              className={cn(
                'h-10 rounded-md border text-[13px] font-medium transition',
                direction === 'in'
                  ? 'bg-emerald-soft border-emerald text-emerald'
                  : 'border-border bg-white text-muted hover:bg-slate-50',
              )}
            >
              <Icon name="arrowDown" size={13} className="inline mr-2" />
              Ingreso
            </button>
            <button
              onClick={() => setDirection('out')}
              className={cn(
                'h-10 rounded-md border text-[13px] font-medium transition',
                direction === 'out'
                  ? 'bg-red-soft border-red text-red'
                  : 'border-border bg-white text-muted hover:bg-slate-50',
              )}
            >
              <Icon name="arrowUp" size={13} className="inline mr-2" />
              Egreso
            </button>
          </div>
        </div>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <Label>Cantidad ({item.unit})</Label>
            <Input
              type="number"
              min="1"
              value={qty}
              onChange={(e) => setQty(Number(e.target.value))}
            />
          </div>
          <div>
            <Label>Nuevo stock</Label>
            <Input
              disabled
              value={direction === 'in' ? item.qty + qty : item.qty - qty}
              className="bg-slate-50 tnum font-semibold"
            />
          </div>
        </div>
        <div>
          <Label>Motivo / observación</Label>
          <Textarea
            rows={2}
            placeholder={
              direction === 'in' ? 'Ej: Compra orden 1420' : 'Ej: Utilizado en pozo NETTO'
            }
            value={reason}
            onChange={(e) => setReason(e.target.value)}
          />
        </div>
      </div>
    </Dialog>
  );
}

Object.assign(window, { StockModule });
