"use client";

/*
 * Pedido › "O que saiu do estoque" (só no estoque novo): por item do pedido,
 * cada célula que ele tirou (e devolveu, se cancelou ou mudou), com o link
 * para o item no estoque. Empresa fora do v2: não aparece nada.
 */

import { useEffect, useState } from "react";
import Link from "next/link";
import { Boxes, ChevronDown } from "lucide-react";
import { nomeDoMovimento, qtd, qtdComSinal, unidade } from "@/lib/estoque/regras";
import type { BaixaDoItem } from "@/lib/estoque/tipos";

type Resposta = {
  v2: boolean;
  itens: Array<{ item_pedido_id: string; titulo: string | null; quantidade: number; produto_id: string | null; baixas: BaixaDoItem[]; erro: string | null }>;
};

const DATA = new Intl.DateTimeFormat("pt-BR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });

export function EstoqueDoPedido({ pedidoId, recarregar = 0 }: { pedidoId: string; recarregar?: number }) {
  const [d, setD] = useState<Resposta | null>(null);
  const [aberto, setAberto] = useState<string | null>(null);

  useEffect(() => {
    let vivo = true;
    fetch(`/api/estoque/pedido/${pedidoId}`, { cache: "no-store" })
      .then((r) => (r.ok ? r.json() : null))
      .then((j) => vivo && setD(j as Resposta | null))
      .catch(() => undefined);
    return () => {
      vivo = false;
    };
  }, [pedidoId, recarregar]);

  if (!d) return null;
  if (!d.v2) return null;

  const algum = d.itens.some((i) => i.baixas.length);

  return (
    <div className="overflow-hidden rounded-xl border border-[var(--ks-color-border-subtle)] bg-[var(--ks-color-bg-elevated)]">
      <div className="flex items-center justify-between gap-3 border-b border-[var(--ks-color-border-subtle)] px-6 py-4">
        <div className="flex items-center gap-3">
          <span
            className="flex h-9 w-9 items-center justify-center rounded-xl text-white"
            style={{ background: "linear-gradient(135deg, var(--ks-brand-500) 0%, var(--ks-brand-700) 100%)" }}
          >
            <Boxes size={17} />
          </span>
          <div>
            <h3 className="text-lg font-semibold text-[var(--ks-color-text-primary)]">O que saiu do estoque</h3>
            <p className="text-xs text-[var(--ks-color-text-muted)]">Gravado na venda: cancelar ou mudar o item devolve exatamente isto.</p>
          </div>
        </div>
      </div>
      {!algum ? (
        <p className="px-6 py-5 text-sm text-[var(--ks-color-text-muted)]">
          Nada saiu do estoque neste pedido (produtos que não controlam, ou o pedido ainda não foi aprovado).
        </p>
      ) : (
        <ul>
          {d.itens.map((it) => {
            const liquido = it.baixas.filter((b) => (b.baixado ?? 0) !== 0);
            return (
              <li key={it.item_pedido_id} className="border-t border-slate-100/60 px-6 py-3 first:border-t-0">
                <div className="flex flex-wrap items-baseline justify-between gap-2">
                  <p className="text-sm font-semibold text-[var(--ks-color-text-primary)]">
                    {it.titulo ?? "Item"} <span className="font-normal text-[var(--ks-color-text-muted)]">× {qtd(it.quantidade)}</span>
                  </p>
                  {it.baixas.length ? (
                    <button
                      type="button"
                      onClick={() => setAberto(aberto === it.item_pedido_id ? null : it.item_pedido_id)}
                      className="flex items-center gap-1 text-xs font-semibold text-[var(--ks-color-primary)]"
                    >
                      Movimentos <ChevronDown size={13} className={aberto === it.item_pedido_id ? "rotate-180" : ""} />
                    </button>
                  ) : null}
                </div>
                {it.baixas.length === 0 ? (
                  <p className="text-xs text-[var(--ks-color-text-soft)]">não mexe no estoque</p>
                ) : (
                  <div className="mt-1 flex flex-wrap gap-1.5">
                    {(liquido.length ? liquido : it.baixas).map((b, i) => (
                      <Link
                        key={b.celula?.celula_id ?? i}
                        href={b.celula ? `/dashboard/products/estoque?aba=${b.celula.papel === "pronto" ? "prontos" : "insumos"}&item=${b.celula.item_id}` : "/dashboard/products/estoque"}
                        className="inline-flex items-center gap-1.5 rounded-full bg-[var(--ks-color-bg-subtle)] px-2.5 py-1 text-xs text-[var(--ks-color-text-secondary)] hover:bg-[var(--ks-brand-50)] hover:text-[var(--ks-brand-700)]"
                      >
                        <span className="font-semibold">{b.celula?.rotulo ?? "Item"}</span>
                        <span className={`ks-num font-bold ${(b.baixado ?? 0) > 0 ? "text-rose-600" : "text-slate-500"}`}>
                          {(b.baixado ?? 0) !== 0 ? `−${qtd(b.baixado)}` : "devolvido"} {unidade(b.celula?.unidade)}
                        </span>
                      </Link>
                    ))}
                  </div>
                )}
                {aberto === it.item_pedido_id ? (
                  <ul className="mt-2 rounded-xl bg-[var(--ks-color-bg-subtle)]/60 px-3 py-2">
                    {it.baixas.flatMap((b) =>
                      b.movimentos.map((m) => (
                        <li key={m.id} className="flex flex-wrap items-center justify-between gap-2 py-1 text-xs">
                          <span className="text-[var(--ks-color-text-secondary)]">
                            {DATA.format(new Date(m.em))} · {nomeDoMovimento(m.tipo, Number(m.quantidade))} · {b.celula?.rotulo}
                            {m.observacao ? <span className="italic text-[var(--ks-color-text-soft)]"> · {m.observacao}</span> : null}
                          </span>
                          <span className={`ks-num font-bold ${Number(m.quantidade) < 0 ? "text-rose-600" : "text-emerald-600"}`}>
                            {qtdComSinal(Number(m.quantidade))} <span className="font-normal text-slate-400">fica {qtd(m.saldo_depois)}</span>
                          </span>
                        </li>
                      ))
                    )}
                  </ul>
                ) : null}
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}
