"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { supabase } from "@/lib/supabase";
import JsBarcode from "jsbarcode";
import QRCode from "qrcode";
import PrintButton from "@/components/print/PrintButton";

type Guia = {
  id: number | string;
  numero?: string;
  numero_guia?: string;
  cliente?: string;
  ciudad?: string;
  telefono?: string;
  direccion?: string;
  estado?: string;
};

type Caja = {
  id: number | string;
  numero_caja?: number | string;
  largo?: number | string;
  ancho?: number | string;
  alto?: number | string;
  peso?: number | string;
};

export default function EtiquetaPage() {
  const params = useParams();

  const id = Array.isArray(params?.id)
    ? params.id[0]
    : params?.id;

  const [guia, setGuia] = useState<Guia | null>(null);
  const [cajas, setCajas] = useState<Caja[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [siteUrl, setSiteUrl] = useState("");
  const [qrDataUrls, setQrDataUrls] = useState<Record<string, string>>({});
  const [scale, setScale] = useState(1);

  useEffect(() => {
    if (typeof window !== "undefined") {
      setSiteUrl(window.location.origin);

      function updateScale() {
        const labelWidthPx = 4 * 96; // 4in a ~96px/in
        const containerPadding = 36; // 18px a cada lado
        const available = window.innerWidth - containerPadding;
        const nextScale = Math.min(1, Math.max(0.72, available / labelWidthPx));
        setScale(Number(nextScale.toFixed(3)));
      }

      updateScale();
      window.addEventListener("resize", updateScale);
      return () => window.removeEventListener("resize", updateScale);
    }
  }, []);

  useEffect(() => {
    if (!id) {
      setError("No se recibió un ID válido para la guía.");
      setLoading(false);
      return;
    }

    cargarDatos();
  }, [id]);

  useEffect(() => {
    if (!siteUrl || !guia) return;

    const numeroGuia =
      guia.numero_guia || guia.numero || `HCE${guia.id}`;

    async function generarQrs() {
      const map: Record<string, string> = {};
      const cajasFinales =
        cajas.length > 0
          ? cajas
          : [
              {
                id: "sin-caja",
                numero_caja: 1,
                largo: "-",
                ancho: "-",
                alto: "-",
                peso: "",
              },
            ];

      for (let i = 0; i < cajasFinales.length; i++) {
        const caja = cajasFinales[i];
        const numeroCaja = caja.numero_caja || i + 1;
        const qrContenido =
          `${siteUrl}/cargoerp/rastreo/${encodeURIComponent(
            numeroGuia
          )}?caja=${encodeURIComponent(String(numeroCaja))}`;

        try {
          const dataUrl = await QRCode.toDataURL(qrContenido, {
            width: 180,
            margin: 0,
            errorCorrectionLevel: "M",
            color: { dark: "#111827", light: "#ffffff" },
          });
          map[String(caja.id || i)] = dataUrl;
        } catch (err) {
          // eslint-disable-next-line no-console
          console.error("Error generando QR:", err);
        }
      }

      setQrDataUrls(map);
    }

    generarQrs();
  }, [siteUrl, guia, cajas]);

  async function cargarDatos() {
    try {
      setLoading(true);
      setError("");

      const {
        data: guiaData,
        error: guiaError,
      } = await supabase
        .from("hce_guias")
        .select("*")
        .eq("id", id)
        .maybeSingle();

      if (guiaError) {
        throw new Error(guiaError.message);
      }

      if (!guiaData) {
        throw new Error(
          `No se encontró ninguna guía con el ID ${id}.`
        );
      }

      setGuia(guiaData);

      const {
        data: cajasData,
        error: cajasError,
      } = await supabase
        .from("hce_cajas")
        .select("*")
        .eq("guia_id", id)
        .order("id", {
          ascending: true,
        });

      if (cajasError) {
        console.warn(
          "No se pudieron cargar las cajas:",
          cajasError.message
        );

        setCajas([]);
      } else {
        setCajas(cajasData || []);
      }
    } catch (err: any) {
      console.error(
        "Error cargando etiqueta:",
        err
      );

      setError(
        err?.message ||
          "Ocurrió un error al cargar la etiqueta."
      );
    } finally {
      setLoading(false);
    }
  }

  if (loading) {
    return (
      <main
        style={{
          minHeight: "100vh",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          background: "#d1d5db",
          fontFamily: "Arial, Helvetica, sans-serif",
        }}
      >
        <div
          style={{
            background: "#111827",
            color: "#ffffff",
            padding: "18px 24px",
            borderRadius: "12px",
            fontWeight: 800,
          }}
        >
          Cargando etiqueta...
        </div>
      </main>
    );
  }

  if (error || !guia) {
    return (
      <main
        style={{
          minHeight: "100vh",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          background: "#d1d5db",
          padding: "24px",
          fontFamily: "Arial, Helvetica, sans-serif",
        }}
      >
        <div
          style={{
            background: "#7f1d1d",
            color: "#ffffff",
            padding: "24px",
            borderRadius: "16px",
            maxWidth: "500px",
            textAlign: "center",
          }}
        >
          <h2
            style={{
              margin: "0 0 12px",
              fontSize: "22px",
              fontWeight: 900,
            }}
          >
            Error al cargar la etiqueta
          </h2>

          <p style={{ margin: 0 }}>
            {error || "No se encontró la guía."}
          </p>
        </div>
      </main>
    );
  }

  const cajasFinales: Caja[] =
    cajas.length > 0
      ? cajas
      : [
          {
            id: "sin-caja",
            numero_caja: 1,
            largo: "-",
            ancho: "-",
            alto: "-",
            peso: "",
          },
        ];

  const numeroGuia =
    guia.numero_guia ||
    guia.numero ||
    `HCE${id}`;

  const qrListo = cajasFinales.every(
    (caja, index) => qrDataUrls[String(caja.id || index)]
  );

  return (
    <>
      <style>{`

        @page {
          size: 4in 6in;
          margin: 0;
        }

        *,
        *::before,
        *::after {
          box-sizing: border-box;
        }

        html,
        body {
          margin: 0;
          padding: 0;
          width: 100%;
          min-height: 100%;
          background: #d1d5db;
          font-family: Arial, Helvetica, sans-serif;
        }

        body {
          overflow-x: hidden;
        }

        .contenedor-etiquetas {
          width: 100%;
          min-height: 100vh;
          padding: 18px;
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 16px;
        }

        .etiqueta {
          width: 4in;
          height: 6in;
          min-width: 4in;
          min-height: 6in;
          max-width: 4in;
          max-height: 6in;
          background: #ffffff;
          color: #111827;
          overflow: hidden;
          position: relative;
          box-shadow: 0 10px 30px rgba(0,0,0,.18);
          display: flex;
          flex-direction: column;
          transform: scale(var(--etiqueta-scale, 1));
          transform-origin: top center;
        }

        .no-print {
          width: auto;
          max-width: 4in;
          display: flex;
          justify-content: center;
          margin-bottom: 0;
        }

        .btn-imprimir {
          border: none;
          background: #111827;
          color: white;
          padding: 12px 22px;
          border-radius: 10px;
          font-weight: 800;
          font-size: 15px;
          cursor: pointer;
          text-decoration: none;
          text-align: center;
          display: inline-flex;
          align-items: center;
          justify-content: center;
        }

        .btn-imprimir:hover {
          background: #000000;
        }

        @media screen and (max-width: 420px) {
          .contenedor-etiquetas {
            padding: 10px;
            gap: 8px;
          }

          .no-print {
            width: 100%;
            max-width: 100%;
          }
        }

        @media print {
          html,
          body {
            width: 4in !important;
            min-height: 0 !important;
            margin: 0 !important;
            padding: 0 !important;
            background: white !important;
            overflow-x: visible !important;
          }

          body {
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
          }

          .contenedor-etiquetas {
            display: block !important;
            width: 4in !important;
            min-height: 0 !important;
            margin: 0 !important;
            padding: 0 !important;
            background: white !important;
            gap: 0 !important;
          }

          .no-print {
            display: none !important;
          }

          .etiqueta {
            width: 4in !important;
            height: 6in !important;
            min-width: 4in !important;
            min-height: 6in !important;
            max-width: 4in !important;
            max-height: 6in !important;
            margin: 0 !important;
            padding: 0 !important;
            border: none !important;
            box-shadow: none !important;
            overflow: hidden !important;
            transform: none !important;
            page-break-after: always;
            break-after: page;
          }

          .etiqueta:last-child {
            page-break-after: auto;
            break-after: auto;
          }
        }

      `}</style>

      <main
        className="contenedor-etiquetas"
        style={{ "--etiqueta-scale": scale } as React.CSSProperties}
      >

        <div className="no-print" style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "10px" }}>
          <a href="/cargoerp/guias" className="btn-imprimir">
            ← Volver a Guías
          </a>
          <PrintButton
            mode="etiqueta"
            label="🖨️ IMPRIMIR"
            onFallback={() => window.print()}
            disabled={!qrListo}
          />
        </div>

        {cajasFinales.map(
          (caja: Caja, index: number) => {

            const numeroCaja =
              caja.numero_caja ||
              index + 1;

            const codigoCaja =
              `${numeroGuia}-${numeroCaja}`;

            const qrDataUrl =
              qrDataUrls[String(caja.id || index)] ||
              "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";

            const barcodeId =
              `barcode-${index}-${String(caja.id)}`;

            return (
              <section
                key={String(caja.id || index)}
                className="etiqueta"
              >

                {/* ENCABEZADO */}

                <div
                  style={{
                    padding:
                      "0.13in 0.18in 0.09in",
                    borderBottom:
                      "2px solid #111827",
                    flexShrink: 0,
                  }}
                >
                  <div
                    style={{
                      fontSize: "20px",
                      fontWeight: 900,
                      letterSpacing:
                        "1.3px",
                      lineHeight: 1,
                    }}
                  >
                    HONDURAS
                  </div>

                  <div
                    style={{
                      fontSize: "20px",
                      fontWeight: 900,
                      letterSpacing:
                        "1.3px",
                      marginTop: "2px",
                      lineHeight: 1,
                    }}
                  >
                    CARGO
                  </div>

                  <div
                    style={{
                      fontSize: "8px",
                      fontWeight: 800,
                      letterSpacing:
                        "2.5px",
                      marginTop: "5px",
                    }}
                  >
                    EXPRESS
                  </div>
                </div>

                {/* TIPO */}

                <div
                  style={{
                    background:
                      "#000000",
                    color: "#FFFFFF",
                    textAlign:
                      "center",
                    padding:
                      "4px 8px",
                    fontWeight: 900,
                    fontSize: "12px",
                    letterSpacing:
                      ".8px",
                    flexShrink: 0,
                  }}
                >
                  GUÍA DE ENVÍO
                </div>

                {/* NÚMERO DE GUÍA */}

                <div
                  style={{
                    textAlign:
                      "center",
                    padding:
                      "0.10in 0.18in",
                    borderBottom:
                      "2px solid #111827",
                    flexShrink: 0,
                  }}
                >
                  <div
                    style={{
                      fontSize: "17px",
                      fontWeight: 900,
                      letterSpacing:
                        ".7px",
                      lineHeight: 1,
                    }}
                  >
                    {numeroGuia}
                  </div>
                </div>

                {/* DESTINATARIO */}

                <div
                  style={{
                    padding:
                      "0.11in 0.18in 0.08in",
                    flexShrink: 0,
                  }}
                >

                  <div
                    style={{
                      fontSize: "8px",
                      fontWeight: 900,
                      letterSpacing:
                        ".7px",
                      marginBottom: "3px",
                    }}
                  >
                    DESTINATARIO
                  </div>

                  <div
                    style={{
                      fontSize: "20px",
                      fontWeight: 900,
                      lineHeight: 1.05,
                      wordBreak:
                        "break-word",
                    }}
                  >
                    {guia.cliente || "-"}
                  </div>

                </div>

                {/* CIUDAD / TELÉFONO */}

                <div
                  style={{
                    display: "grid",
                    gridTemplateColumns:
                      "1fr 1fr",
                    gap: "10px",
                    padding:
                      "0 0.18in 0.08in",
                    flexShrink: 0,
                  }}
                >

                  <div>

                    <div
                      style={{
                        fontSize: "8px",
                        fontWeight: 900,
                        marginBottom: "3px",
                        letterSpacing:
                          ".7px",
                      }}
                    >
                      CIUDAD
                    </div>

                    <div
                      style={{
                        fontSize: "14px",
                        fontWeight: 900,
                        lineHeight: 1.05,
                        wordBreak:
                          "break-word",
                      }}
                    >
                      {guia.ciudad || "-"}
                    </div>

                  </div>

                  <div style={{ minWidth: 0 }}>

                    <div
                      style={{
                        fontSize: "8px",
                        fontWeight: 900,
                        marginBottom: "3px",
                        letterSpacing:
                          ".7px",
                      }}
                    >
                      TELÉFONO
                    </div>

                    <div
                      style={{
                        fontSize:
                          (guia.telefono || "").length > 18
                            ? "10px"
                            : (guia.telefono || "").length > 12
                            ? "12px"
                            : "14px",
                        fontWeight: 900,
                        whiteSpace: "nowrap",
                        overflow: "visible",
                      }}
                    >
                      {guia.telefono || "-"}
                    </div>

                  </div>

                </div>

                {/* DIRECCIÓN */}

                <div
                  style={{
                    padding:
                      "0 0.18in 0.09in",
                    borderBottom:
                      "2px solid #111827",
                    flexShrink: 0,
                  }}
                >

                  <div
                    style={{
                      fontSize: "8px",
                      fontWeight: 900,
                      marginBottom: "3px",
                      letterSpacing:
                        ".7px",
                    }}
                  >
                    DIRECCIÓN
                  </div>

                  <div
                    style={{
                      fontSize: "13px",
                      fontWeight: 800,
                      lineHeight: 1.1,
                      wordBreak:
                        "break-word",
                      maxHeight: "46px",
                      overflow: "hidden",
                    }}
                  >
                    {guia.direccion || "-"}
                  </div>

                </div>

                {/* ESTADO / CAJA */}

                <div
                  style={{
                    display: "grid",
                    gridTemplateColumns:
                      "1fr 1fr",
                    padding:
                      "0.09in 0.18in 0.07in",
                    gap: "10px",
                    flexShrink: 0,
                  }}
                >

                  <div>

                    <div
                      style={{
                        fontSize: "8px",
                        fontWeight: 900,
                        marginBottom: "3px",
                        letterSpacing:
                          ".7px",
                      }}
                    >
                      ESTADO
                    </div>

                    <div
                      style={{
                        fontSize: "14px",
                        fontWeight: 900,
                        lineHeight: 1.05,
                      }}
                    >
                      {guia.estado || "Recibida"}
                    </div>

                  </div>

                  <div>

                    <div
                      style={{
                        fontSize: "8px",
                        fontWeight: 900,
                        marginBottom: "3px",
                        letterSpacing:
                          ".7px",
                      }}
                    >
                      CAJA
                    </div>

                    <div
                      style={{
                        fontSize: "14px",
                        fontWeight: 900,
                      }}
                    >
                      {numeroCaja}/
                      {cajasFinales.length}
                    </div>

                  </div>

                </div>

                {/* MEDIDAS */}

                <div
                  style={{
                    margin:
                      "0 0.18in",
                    border:
                      "2px solid #111827",
                    textAlign:
                      "center",
                    padding:
                      "0.05in 0.05in",
                    flexShrink: 0,
                  }}
                >

                  <div
                    style={{
                      fontSize: "8px",
                      fontWeight: 900,
                      letterSpacing:
                        ".8px",
                      marginBottom: "3px",
                    }}
                  >
                    MEDIDAS
                  </div>

                  <div
                    style={{
                      fontSize: "20px",
                      fontWeight: 900,
                      letterSpacing:
                        ".2px",
                      lineHeight: 1,
                    }}
                  >
                    {caja.largo || "-"}" ×{" "}
                    {caja.ancho || "-"}" ×{" "}
                    {caja.alto || "-"}"
                  </div>

                  {caja.peso && (
                    <div
                      style={{
                        marginTop: "4px",
                        fontSize: "10px",
                        fontWeight: 800,
                      }}
                    >
                      PESO: {caja.peso}
                    </div>
                  )}

                </div>

                {/* CÓDIGOS */}

                <div
                  style={{
                    flex: 1,
                    minHeight: 0,
                    display: "flex",
                    flexDirection:
                      "column",
                    alignItems:
                      "center",
                    justifyContent:
                      "flex-end",
                    padding:
                      "0.04in 0.18in 0.08in",
                  }}
                >

                  {/* CÓDIGO DE BARRAS */}

                  <svg
                    id={barcodeId}
                    ref={(element) => {
                      if (!element) {
                        return;
                      }

                      try {
                        JsBarcode(
                          element,
                          codigoCaja,
                          {
                            format: "CODE128",
                            width: 1.5,
                            height: 38,
                            displayValue: false,
                            margin: 0,
                            background: "#ffffff",
                            lineColor: "#111827",
                          }
                        );
                      } catch (error) {
                        console.error(
                          "Error generando código de barras:",
                          error
                        );
                      }
                    }}
                    style={{
                      width: "235px",
                      height: "42px",
                      display: "block",
                      flexShrink: 0,
                    }}
                  />

                  {/* TEXTO DEL CÓDIGO */}

                  <div
                    style={{
                      fontSize: "12px",
                      fontWeight: 900,
                      letterSpacing:
                        "3px",
                      textAlign:
                        "center",
                      marginTop: "2px",
                      lineHeight: 1,
                    }}
                  >
                    {codigoCaja}
                  </div>

                  {/* QR */}

                  <img
                    src={qrDataUrl}
                    alt={`QR ${codigoCaja}`}
                    width={88}
                    height={88}
                    style={{
                      width: "88px",
                      height: "88px",
                      display: "block",
                      marginTop: "4px",
                      flexShrink: 0,
                    }}
                  />

                  <div
                    style={{
                      marginTop: "3px",
                      fontSize: "7px",
                      fontWeight: 800,
                      letterSpacing:
                        "1.5px",
                      textAlign:
                        "center",
                      lineHeight: 1,
                    }}
                  >
                    HONDURAS CARGO EXPRESS
                  </div>

                </div>

              </section>
            );
          }
        )}

      </main>
    </>
  );
}
