"use client";

import { useState } from "react";
import { ShoppingCart, Loader2 } from "lucide-react";
import Button from "@/components/ui/Button";
import { listCorteJobsWithItems } from "@/lib/pb/cortes";
import { groupItemsByMaterial, packCuts, boardSizeFromDims } from "@/lib/cortes/optimizer";
import { getMaterialColorStyle } from "@/lib/cortes/materials";
import { usePreciosStore } from "@/lib/calculadora/store";
import { money } from "@/lib/format";

interface CompraRow {
  key: string;
  label: string;
  code: string;
  color?: string;
  placas: number;
  valorPlaca: number;
  subtotal: number;
}

// Calcula cuánto comprar (placas + costo) para los CORTES PENDIENTES, reusando
// el mismo optimizador del módulo Cortes. Solo cuenta materiales optimizables
// (placas); el precio por placa sale de dimensiones[mat][2] (Lista de precios).
export default function CompraPlacas() {
  const dimensiones = usePreciosStore((s) => s.data.dimensiones);
  const [loading, setLoading] = useState(false);
  const [rows, setRows] = useState<CompraRow[] | null>(null);
  const [err, setErr] = useState("");

  async function calcular() {
    setLoading(true);
    setErr("");
    try {
      const jobs = await listCorteJobsWithItems();
      const groups = groupItemsByMaterial(jobs.flatMap((j) => j.items))
        .filter((g) => g.items.some((it) => it.ancho > 0 && it.alto > 0));
      const result: CompraRow[] = [];
      for (const g of groups) {
        const code = g.items[0]?.material ?? "";
        const placas = packCuts(g.items, { board: boardSizeFromDims(code, dimensiones) }).length;
        if (!placas) continue; // material no optimizable o sin placas
        const valorPlaca = dimensiones[code]?.[2] ?? 0;
        result.push({
          key: g.key,
          label: g.label,
          code,
          color: g.items[0]?.color,
          placas,
          valorPlaca,
          subtotal: placas * valorPlaca,
        });
      }
      setRows(result);
    } catch (e) {
      setErr((e as Error).message || "No se pudo calcular la compra");
    } finally {
      setLoading(false);
    }
  }

  const total = (rows ?? []).reduce((s, r) => s + r.subtotal, 0);
  const totalPlacas = (rows ?? []).reduce((s, r) => s + r.placas, 0);

  return (
    <section className="card space-y-4 p-5">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h3 className="flex items-center gap-2 text-base font-extrabold text-ink">
            <ShoppingCart className="h-5 w-5 text-brand-dark" /> Compra de placas — cortes pendientes
          </h3>
          <p className="text-sm text-ink-soft">
            Calcula las placas a comprar y su costo para cubrir todos los cortes pendientes,
            usando el optimizador de Cortes y la lista de precios.
          </p>
        </div>
        <Button type="button" onClick={calcular} loading={loading}>
          Calcular compra
        </Button>
      </div>

      {err && <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-bad">{err}</div>}

      {loading && (
        <div className="grid place-items-center py-8 text-faint">
          <Loader2 className="h-6 w-6 animate-spin" />
        </div>
      )}

      {!loading && rows && rows.length === 0 && (
        <div className="rounded-xl border border-line bg-surface px-4 py-6 text-center text-sm text-faint">
          No hay placas pendientes para comprar.
        </div>
      )}

      {!loading && rows && rows.length > 0 && (
        <div className="overflow-hidden rounded-xl border border-line">
          <table className="w-full text-sm">
            <thead className="bg-canvas text-[11px] font-bold uppercase text-faint">
              <tr>
                <th className="px-3 py-2 text-left">Material</th>
                <th className="px-3 py-2 text-right">Placas</th>
                <th className="px-3 py-2 text-right">Precio placa</th>
                <th className="px-3 py-2 text-right">Subtotal</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-line bg-surface">
              {rows.map((r) => {
                const s = getMaterialColorStyle(r.code, r.color);
                return (
                  <tr key={r.key}>
                    <td className="px-3 py-2">
                      <span
                        className="rounded-md border px-1.5 py-0.5 text-[11px] font-bold leading-none"
                        style={{ backgroundColor: s.bg, color: s.text, borderColor: s.border }}
                      >
                        {r.label}
                      </span>
                    </td>
                    <td className="px-3 py-2 text-right font-bold tabular-nums text-ink">{r.placas}</td>
                    <td className="px-3 py-2 text-right tabular-nums text-ink-soft">
                      {r.valorPlaca > 0 ? money(r.valorPlaca) : "—"}
                    </td>
                    <td className="px-3 py-2 text-right font-extrabold tabular-nums text-ink">{money(r.subtotal)}</td>
                  </tr>
                );
              })}
            </tbody>
            <tfoot className="bg-canvas">
              <tr className="font-extrabold text-ink">
                <td className="px-3 py-2.5">Total</td>
                <td className="px-3 py-2.5 text-right tabular-nums">{totalPlacas} placa{totalPlacas !== 1 ? "s" : ""}</td>
                <td className="px-3 py-2.5" />
                <td className="px-3 py-2.5 text-right tabular-nums text-good">{money(total)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      )}
    </section>
  );
}
