"use client";

import { useFlagsConfiguracion } from "@/hooks/use-flags-configuracion";
import { formatCurrency, formatDateTime } from "@/lib/utils";
import { normalizePrintAssetUrl } from "@/lib/print";

interface EntregaPrintProps {
  ot: any;
  cliente: any;
  companyName?: string;
}

// Precio unitario con IVA incluido, para que cuadre con el subtotal de la línea
// (la entrega ya no muestra el desglose de IVA).
function getLineUnitTotal(linea: any) {
  const cantidad = Number(linea?.cantidad || 0);
  if (cantidad > 0) {
    return Number(linea?.total || 0) / cantidad;
  }

  return Number(linea?.total || 0);
}

function formatNivelGasolina(valor: unknown) {
  if (valor === null || valor === undefined || valor === "") return "-";
  return `${Number(valor)}%`;
}

function formatKm(valor: unknown) {
  if (valor === null || valor === undefined || valor === "") return "-";
  return `${Number(valor).toLocaleString()} km`;
}

export default function EntregaPrint({ ot, cliente, companyName }: EntregaPrintProps) {
  const flags = useFlagsConfiguracion();
  const vehiculo = ot?.vehiculo || {};
  const firma = ot?.firma;
  const cotizacion = ot?.cotizaciones?.[0];
  const lineas = cotizacion?.lineas || [];
  // Servicios primero y luego repuestos, en una sola tabla de "Trabajo Realizado".
  const trabajo = [
    ...lineas.filter((l: any) => l.esServicio),
    ...lineas.filter((l: any) => !l.esServicio),
  ];
  const tienda = ot?.tienda || {};
  const nombreImpresion =
    tienda.nombreImpresion || tienda.nombre || companyName || "Taller Mecánico";
  const direccionImpresion = tienda.direccionImpresion || tienda.direccion || "";
  const telefonoImpresion = tienda.telefonoImpresion || "";
  const logoUrl = normalizePrintAssetUrl(tienda.logoUrl);

  return (
    <div className="print-document print-document-entrega">
      {/* Header */}
      <header className="print-header print-header-branded">
        <div className="print-header-left">
          {logoUrl ? (
            <img src={logoUrl} alt={nombreImpresion} className="print-store-logo" />
          ) : (
            <h1 className="print-company-name">{nombreImpresion}</h1>
          )}
          {direccionImpresion ? (
            <p className="print-store-address">{direccionImpresion}</p>
          ) : null}
          {telefonoImpresion ? (
            <p className="print-store-phone">Tel: {telefonoImpresion}</p>
          ) : null}
          <p className="print-subtitle">Comprobante de Entrega de Vehículo</p>
        </div>
        <div className="print-header-right">
          <div className="print-badge">{ot?.numeroOt || "Sin número"}</div>
          <p className="print-date">
            Entrega: {ot?.fechaSalida ? formatDateTime(ot.fechaSalida) : "Pendiente"}
          </p>
        </div>
      </header>

      <div className="print-divider" />

      {/* Client + Vehicle Grid */}
      <div className="print-grid-2">
        <section className="print-section">
          <h2 className="print-section-title">Datos del Cliente</h2>
          <table className="print-info-table">
            <tbody>
              <tr>
                <td className="print-label">Nombre</td>
                <td className="print-value">{cliente?.nombre || ot?.clienteTarjeta || "-"}</td>
              </tr>
              <tr>
                <td className="print-label">Tarjeta</td>
                <td className="print-value">{ot?.clienteTarjeta || "-"}</td>
              </tr>
              {cliente?.telefono ? (
                <tr>
                  <td className="print-label">Teléfono</td>
                  <td className="print-value">{cliente.telefono}</td>
                </tr>
              ) : null}
              {cliente?.celular ? (
                <tr>
                  <td className="print-label">Celular</td>
                  <td className="print-value">{cliente.celular}</td>
                </tr>
              ) : null}
              {cliente?.email ? (
                <tr>
                  <td className="print-label">Correo</td>
                  <td className="print-value">{cliente.email}</td>
                </tr>
              ) : null}
              {cliente?.nit ? (
                <tr>
                  <td className="print-label">NIT</td>
                  <td className="print-value">{cliente.nit}</td>
                </tr>
              ) : null}
            </tbody>
          </table>
        </section>

        <section className="print-section">
          <h2 className="print-section-title">Datos del Vehículo</h2>
          <table className="print-info-table">
            <tbody>
              <tr>
                <td className="print-label">Placa</td>
                <td className="print-value print-value-bold">{vehiculo.placa || "-"}</td>
              </tr>
              <tr>
                <td className="print-label">Marca / Modelo</td>
                <td className="print-value">
                  {vehiculo.marca || "-"} {vehiculo.modelo || ""}
                </td>
              </tr>
              {flags.usaMecanicos && ot?.mecanico?.nombre ? (
                <tr>
                  <td className="print-label">Mecánico</td>
                  <td className="print-value">{ot.mecanico.nombre}</td>
                </tr>
              ) : null}
            </tbody>
          </table>
        </section>
      </div>

      {/* Entrada y entrega: fecha, kilometraje y gasolina de cada momento */}
      <div className="print-grid-2">
        <section className="print-section">
          <h2 className="print-section-title">Fecha de Entrada</h2>
          <table className="print-info-table">
            <tbody>
              <tr>
                <td className="print-label">Fecha</td>
                <td className="print-value">{ot?.fechaEntrada ? formatDateTime(ot.fechaEntrada) : "-"}</td>
              </tr>
              <tr>
                <td className="print-label">Kilometraje</td>
                <td className="print-value">{formatKm(ot?.km ?? 0)}</td>
              </tr>
              <tr>
                <td className="print-label">Gasolina</td>
                <td className="print-value">{formatNivelGasolina(ot?.nivelGasolina ?? 0)}</td>
              </tr>
            </tbody>
          </table>
        </section>
        <section className="print-section">
          <h2 className="print-section-title">Fecha de Entrega</h2>
          <table className="print-info-table">
            <tbody>
              <tr>
                <td className="print-label">Fecha</td>
                <td className="print-value print-value-bold">
                  {ot?.fechaSalida ? formatDateTime(ot.fechaSalida) : "Pendiente"}
                </td>
              </tr>
              <tr>
                <td className="print-label">Kilometraje</td>
                <td className="print-value print-value-bold">{formatKm(ot?.kmSalida)}</td>
              </tr>
              <tr>
                <td className="print-label">Gasolina</td>
                <td className="print-value print-value-bold">{formatNivelGasolina(ot?.nivelGasolinaSalida)}</td>
              </tr>
            </tbody>
          </table>
        </section>
      </div>

      {/* Detail of what was actually done, with prices — the approved quotation */}
      {cotizacion ? (
        <section className="print-section print-section-flow">
          <h2 className="print-section-title">Trabajo Realizado</h2>
          {trabajo.length > 0 ? (
            <table className="print-table">
              <thead>
                <tr>
                  <th className="print-col-narrow">#</th>
                  <th className="print-col-code">Código</th>
                  <th>Descripción</th>
                  <th className="print-col-number">Cantidad</th>
                  <th className="print-col-number">Precio Unit.</th>
                  <th className="print-col-number">Subtotal</th>
                </tr>
              </thead>
              <tbody>
                {trabajo.map((l: any, i: number) => (
                  <tr key={l.id || i}>
                    <td className="print-col-narrow">{i + 1}</td>
                    <td className="print-col-code print-mono">{l.plu}</td>
                    <td>{l.descripcion}</td>
                    <td className="print-col-number">{Number(l.cantidad || 0).toLocaleString()}</td>
                    <td className="print-col-number">{formatCurrency(getLineUnitTotal(l))}</td>
                    <td className="print-col-number">{formatCurrency(Number(l.total || 0))}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <p className="print-empty">No hay trabajo registrado en la cotización.</p>
          )}

          <div className="print-totals">
            <div className="print-total-row print-total-grand">
              <span>Total</span>
              <span>{formatCurrency(Number(cotizacion.total || 0))}</span>
            </div>
          </div>
        </section>
      ) : (
        <section className="print-section">
          <h2 className="print-section-title">Trabajo Realizado</h2>
          <p className="print-empty">No hay una cotización registrada en esta orden.</p>
        </section>
      )}

      {/* Recomendaciones capturadas al entregar: debajo del total, arriba de las firmas */}
      {ot?.recomendacionesEntrega ? (
        <section className="print-section print-recomendaciones">
          <h2 className="print-section-title">Recomendaciones / Observaciones</h2>
          <p className="print-text-block">{ot.recomendacionesEntrega}</p>
        </section>
      ) : null}

      {/* Signatures */}
      <div className="print-signatures">
        {flags.usaFirmaCliente ? (
          <div className="print-signature-block">
            {firma?.firmaCliente ? (
              <img src={normalizePrintAssetUrl(firma.firmaCliente)} alt="Firma del cliente" className="print-signature-img" />
            ) : (
              <div className="print-signature-line" />
            )}
            <p className="print-signature-label">
              {firma?.nombreFirmaCliente || "Recibí conforme (Cliente)"}
            </p>
          </div>
        ) : null}
        <div className="print-signature-block">
          {firma?.firmaEntrega ? (
            <img
              src={normalizePrintAssetUrl(firma.firmaEntrega)}
              alt="Firma de quien entrega"
              className="print-signature-img"
            />
          ) : (
            <div className="print-signature-line" />
          )}
          <p className="print-signature-label">
            {firma?.nombreFirmaEntrega ? `Entregado por: ${firma.nombreFirmaEntrega}` : "Entregado por (Taller)"}
          </p>
        </div>
      </div>

      {/* Internal observations */}
      {ot?.observaciones ? (
        <section className="print-section">
          <h2 className="print-section-title">Observaciones Internas</h2>
          <p className="print-text-block">{ot.observaciones}</p>
        </section>
      ) : null}

      <footer className="print-footer">
        <p>
          Comprobante de entrega {ot?.numeroOt || ""} —{" "}
          {ot?.fechaSalida ? formatDateTime(ot.fechaSalida) : formatDateTime(new Date())}
        </p>
        <p className="print-legal">
          El cliente confirma haber recibido el vehículo conforme a lo indicado en este comprobante.
        </p>
      </footer>
    </div>
  );
}
