"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { supabase } from "@/lib/supabase";
import JsBarcode from "jsbarcode";

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("");

  useEffect(() => {
    if (!id) {
      setError("No se recibió un ID válido para la guía.");
      setLoading(false);
      return;
    }

    cargarDatos();
  }, [id]);

  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 siteUrl =
    typeof window !== "undefined"
      ? window.location.origin
      : "";

  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;
        }

        .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;
        }

        .no-print {
          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;
        }

        .btn-imprimir:hover {
          background: #000000;
        }

        @media print {

          html,
          body {
            width: 4in !important;
            height: 6in !important;
            margin: 0 !important;
            padding: 0 !important;
            background: white !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;
          }

          .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;
            page-break-after: always;
            break-after: page;
          }

          .etiqueta:last-child {
            page-break-after: auto;
            break-after: auto;
          }
        }

      `}</style>

      <main className="contenedor-etiquetas">

        <div className="no-print">
          <button
            type="button"
            className="btn-imprimir"
            onClick={() => window.print()}
          >
            IMPRIMIR ETIQUETAS
          </button>
        </div>

        {cajasFinales.map(
          (caja: Caja, index: number) => {

            const numeroCaja =
              caja.numero_caja ||
              index + 1;

            const codigoCaja =
              `${numeroGuia}-${numeroCaja}`;

            const qrContenido =
              `${siteUrl}/cargoerp/rastreo/${encodeURIComponent(
                numeroGuia
              )}?caja=${encodeURIComponent(
                String(numeroCaja)
              )}`;

            const qrImage =
              `https://api.qrserver.com/v1/create-qr-code/?` +
              `size=150x150&margin=0&data=` +
              `${encodeURIComponent(qrContenido)}`;

            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={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent:
                        "space-between",
                    }}
                  >

                    <div>

                      <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>

                    <div
                      style={{
                        border:
                          "2px solid #111827",
                        padding:
                          "8px 10px",
                        fontSize: "17px",
                        fontWeight: 900,
                        letterSpacing:
                          ".7px",
                        textAlign:
                          "center",
                      }}
                    >
                      {numeroGuia}
                    </div>

                  </div>
                </div>

                {/* TIPO */}

                <div
                  style={{
                    background:
                      "#f97316",
                    color: "#ffffff",
                    textAlign:
                      "center",
                    padding:
                      "6px 8px",
                    fontWeight: 900,
                    fontSize: "12px",
                    letterSpacing:
                      ".8px",
                    flexShrink: 0,
                  }}
                >
                  GUÍA DE ENVÍO
                </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>

                    <div
                      style={{
                        fontSize: "8px",
                        fontWeight: 900,
                        marginBottom: "3px",
                        letterSpacing:
                          ".7px",
                      }}
                    >
                      TELÉFONO
                    </div>

                    <div
                      style={{
                        fontSize: "14px",
                        fontWeight: 900,
                      }}
                    >
                      {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: "30px",
                      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.07in 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={qrImage}
                    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>
    </>
  );
}