"use client";

import { use, useEffect, useState } from "react";
import Link from "next/link";
import { AlertTriangle, ArrowLeft, Printer } from "lucide-react";
import { api } from "@/lib/api";
import { textoDecimal } from "@/lib/ajustes";
import { cuadraConServidor, lineasOrdenadas, type ReporteOrden } from "@/lib/reporte-orden";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { toast } from "sonner";

const dinero = new Intl.NumberFormat("es-GT", { minimumFractionDigits: 2, maximumFractionDigits: 6 });
const cantidadFmt = new Intl.NumberFormat("es-GT", { maximumFractionDigits: 4 });

/** `—` cuando no hay número, que no es lo mismo que cero. */
function q(valor: number | null | undefined): string {
  return null === valor || undefined === valor ? "—" : dinero.format(valor);
}

function n(valor: number | null | undefined): string {
  return null === valor || undefined === valor ? "—" : cantidadFmt.format(valor);
}

/**
 * El reporte de la orden con el formato del papel de Envaisa (orden 2757): un renglón por movimiento, las cuatro
 * columnas de costo y el cierre de la orden. Es sólo lectura: todo sale de GET /api/ordenes/{id}/reporte y no se
 * recalcula nada acá.
 */
export default function PaginaReporteOrden({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const [reporte, setReporte] = useState<ReporteOrden | null>(null);
  const [fallo, setFallo] = useState(false);

  useEffect(() => {
    let vigente = true;
    api<ReporteOrden>(`/api/ordenes/${id}/reporte`)
      .then((r) => {
        if (vigente) setReporte(r);
      })
      .catch((error: unknown) => {
        if (!vigente) return;
        setFallo(true);
        toast.error(error instanceof Error ? error.message : "No se pudo cargar el reporte de la orden.");
      });
    return () => {
      vigente = false;
    };
  }, [id]);

  if (fallo) {
    return (
      <div className="space-y-3">
        <Button variant="ghost" size="sm" asChild>
          <Link href={`/ordenes/${id}`}>
            <ArrowLeft className="size-4" />
            Orden #{id}
          </Link>
        </Button>
        <Alert variant="destructive">
          <AlertTriangle className="size-4" />
          <AlertTitle>No se pudo cargar el reporte</AlertTitle>
          <AlertDescription>
            No se muestra ningún número porque no se pudo leer del servidor. Volvé a intentar o revisá la orden.
          </AlertDescription>
        </Alert>
      </div>
    );
  }

  if (!reporte) {
    return (
      <div className="space-y-3">
        <Skeleton className="h-9 w-48" />
        <Skeleton className="h-96 w-full" />
      </div>
    );
  }

  const e = reporte.encabezado;
  const lineas = lineasOrdenadas(reporte.lineas);
  const t = reporte.totales;
  const cuadra = cuadraConServidor(reporte);

  return (
    <div className="space-y-5">
      <div className="flex flex-wrap items-center gap-3 print:hidden">
        <Button variant="ghost" size="sm" asChild>
          <Link href={`/ordenes/${id}`}>
            <ArrowLeft className="size-4" />
            Orden #{id}
          </Link>
        </Button>
        <h1 className="text-2xl font-semibold tracking-tight">Reporte de la orden #{reporte.orden}</h1>
        <Button variant="outline" size="sm" className="ml-auto" onClick={() => window.print()}>
          <Printer className="size-4" />
          Imprimir
        </Button>
      </div>
      <h1 className="hidden text-xl font-semibold print:block">Reporte de la orden #{reporte.orden}</h1>

      {cuadra ? null : (
        <Alert variant="destructive">
          <AlertTriangle className="size-4" />
          <AlertTitle>Las líneas no suman lo que dice el servidor</AlertTitle>
          <AlertDescription>
            La suma de las columnas de abajo no coincide con los totales del servidor. No uses este reporte para
            comparar con el papel hasta revisar la orden.
          </AlertDescription>
        </Alert>
      )}

      <Card>
        <CardHeader>
          <CardTitle>Estimados, reales y diferencia</CardTitle>
          <CardDescription>Igual que el encabezado del papel: directos, indirectos y totales de la orden.</CardDescription>
        </CardHeader>
        <CardContent className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead />
                <TableHead className="text-right">Estimados</TableHead>
                <TableHead className="text-right">Reales</TableHead>
                <TableHead className="text-right">Diferencia</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {(
                [
                  ["Directos", reporte.resumen.directos],
                  ["Indirectos", reporte.resumen.indirectos],
                  ["Totales", reporte.resumen.totales],
                ] as const
              ).map(([nombre, fila]) => (
                <TableRow key={nombre}>
                  <TableCell className="font-semibold">{nombre}</TableCell>
                  <TableCell className="text-right">{q(fila.estimado)}</TableCell>
                  <TableCell className="text-right">{q(fila.real)}</TableCell>
                  <TableCell className="text-right">{q(fila.diferencia)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>
            {null === e.producto ? `Orden con ${e.productos.length} productos` : `${e.producto} · ${e.descripcionProducto ?? ""}`}
          </CardTitle>
          <CardDescription>
            Estatus {e.estatus} · costeo {e.tipoCosteo} · línea {e.linea} · referencia {e.referencia}
          </CardDescription>
        </CardHeader>
        <CardContent className="grid gap-2 text-sm sm:grid-cols-2 lg:grid-cols-4">
          <div>Inicio: {e.inicio ?? "—"}</div>
          <div>Producción: {e.fechaProduccion ?? "—"}</div>
          <div>Cerrada: {e.cerradoEn ?? "—"}</div>
          <div>
            Fabricar {n(e.fabricar)} · terminada {n(e.terminada)} · faltante {n(e.faltante)}
          </div>
        </CardContent>
        {e.productos.length > 1 || null === e.producto ? (
          <CardContent className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Producto</TableHead>
                  <TableHead>Descripción</TableHead>
                  <TableHead className="text-right">Por fabricar</TableHead>
                  <TableHead className="text-right">Terminada</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {e.productos.map((p) => (
                  <TableRow key={p.plu}>
                    <TableCell className="font-mono text-xs">{p.plu}</TableCell>
                    <TableCell>{p.descripcion}</TableCell>
                    <TableCell className="text-right">{n(p.fabricar)}</TableCell>
                    <TableCell className="text-right">{n(p.terminada)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        ) : null}
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Movimientos</CardTitle>
          <CardDescription>Costo REAL por columna. «Estimado» es lo que se calculó al planificar.</CardDescription>
        </CardHeader>
        <CardContent className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Movimiento</TableHead>
                <TableHead>Producto</TableHead>
                <TableHead>Código</TableHead>
                <TableHead>Descripción</TableHead>
                <TableHead className="text-right">Almacén</TableHead>
                <TableHead className="text-right">Cantidad</TableHead>
                <TableHead className="text-right">Materiales</TableHead>
                <TableHead className="text-right">Mano de obra</TableHead>
                <TableHead className="text-right">Otros gastos</TableHead>
                <TableHead className="text-right">Indirectos</TableHead>
                <TableHead className="text-right">Estimado</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {lineas.map((l, i) => {
                const cierre = l.movimiento === "Cierre de orden";
                return (
                  <TableRow key={`${l.codigo}-${i}`}>
                    <TableCell>{l.movimiento}</TableCell>
                    <TableCell className="font-mono text-xs">{l.pluProducto ?? "—"}</TableCell>
                    <TableCell className="font-mono text-xs">{l.codigo}</TableCell>
                    <TableCell>{l.descripcion}</TableCell>
                    <TableCell className="text-right">{l.almacen ?? "—"}</TableCell>
                    <TableCell className="text-right">
                      {n(l.cantidad)}
                      {null !== l.cantidadEstimada && l.cantidadEstimada !== l.cantidad ? (
                        <span className="text-muted-foreground"> (est. {n(l.cantidadEstimada)})</span>
                      ) : null}
                    </TableCell>
                    {cierre ? (
                      <TableCell colSpan={4} className="text-right">
                        Producto terminado a inventario: <strong>{q(l.productoTerminado)}</strong>
                      </TableCell>
                    ) : (
                      <>
                        <TableCell className="text-right">{q(l.materiales)}</TableCell>
                        <TableCell className="text-right">{q(l.manoDeObra)}</TableCell>
                        <TableCell className="text-right">{q(l.otros)}</TableCell>
                        <TableCell className="text-right">{q(l.indirectos)}</TableCell>
                      </>
                    )}
                    <TableCell className="text-right">{q(l.estimado)}</TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
            <TableFooter>
              <TableRow>
                <TableCell colSpan={6} className="font-semibold">
                  Totales reales
                </TableCell>
                <TableCell className="text-right font-semibold">{q(t.materiales)}</TableCell>
                <TableCell className="text-right font-semibold">{q(t.manoDeObra)}</TableCell>
                <TableCell className="text-right font-semibold">{q(t.otros)}</TableCell>
                <TableCell className="text-right font-semibold">{q(t.indirectos)}</TableCell>
                <TableCell className="text-right font-semibold">{q(reporte.resumen.totales.estimado)}</TableCell>
              </TableRow>
              <TableRow>
                <TableCell colSpan={6} className="font-semibold">
                  Costo real de la orden
                </TableCell>
                <TableCell colSpan={4} className="text-right font-semibold">
                  {q(t.total)}
                </TableCell>
                <TableCell className="text-right text-muted-foreground">
                  dif. {q(reporte.resumen.totales.diferencia)}
                </TableCell>
              </TableRow>
              <TableRow>
                <TableCell colSpan={6} className="font-semibold">
                  Entradas a inventario (producto terminado) · diferencia de cierre
                </TableCell>
                <TableCell colSpan={4} className="text-right font-semibold">
                  {q(t.entradas)}
                </TableCell>
                <TableCell className="text-right text-muted-foreground">{q(t.diferencia)}</TableCell>
              </TableRow>
            </TableFooter>
          </Table>
        </CardContent>
      </Card>

      {reporte.ajustes && reporte.ajustes.ajustes.length > 0 ? (
        <Card>
          <CardHeader>
            <CardTitle>Ajustes tardíos</CardTitle>
            <CardDescription>
              Costo real congelado al cierre {textoDecimal(reporte.ajustes.costoRealCongelado)} + ajustes{" "}
              {textoDecimal(reporte.ajustes.totalAjustes)} = <strong>{textoDecimal(reporte.ajustes.costoRealAjustado)}</strong>
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Fecha</TableHead>
                  <TableHead>Producto</TableHead>
                  <TableHead>Tipo</TableHead>
                  <TableHead>Concepto</TableHead>
                  <TableHead className="text-right">Valor</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {reporte.ajustes.ajustes.map((a) => (
                  <TableRow key={a.id}>
                    <TableCell>{a.fecha}</TableCell>
                    <TableCell>{a.pluProducto}</TableCell>
                    <TableCell>{a.tipo}</TableCell>
                    <TableCell>{a.concepto}</TableCell>
                    <TableCell className="text-right">{textoDecimal(a.valor)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      ) : null}

      {reporte.avisos.length > 0 ? (
        <Alert>
          <AlertTriangle className="size-4" />
          <AlertTitle>Para tener en cuenta</AlertTitle>
          <AlertDescription>
            <ul className="list-disc pl-5">
              {reporte.avisos.map((a) => (
                <li key={a}>{a}</li>
              ))}
            </ul>
          </AlertDescription>
        </Alert>
      ) : null}
    </div>
  );
}
