﻿"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { supabase } from "@/lib/supabase";

type Guia = {
  id: string;
  numero_guia?: string | null;
  cliente?: string | null;
  ciudad?: string | null;
  direccion?: string | null;
  telefono?: string | null;
  correo?: string | null;
  cajas?: number | string | null;
  estado?: string | null;
  fecha?: string | null;
  created_at?: string | null;
  contenedor_id?: string | null;
  contenedor?: string | null;
  numero_contenedor?: string | null;

  [key: string]: any;
};

type Contenedor = {
  id: string;
  numero?: string | null;
  numero_contenedor?: string | null;
  nombre?: string | null;
  codigo?: string | null;
  fecha_salida?: string | null;
  fecha_llegada?: string | null;

  [key: string]: any;
};

function obtenerFecha(valor?: string | null) {
  if (!valor) return "";

  const fecha = new Date(valor);

  if (isNaN(fecha.getTime())) {
    return valor;
  }

  return fecha.toLocaleDateString("es-HN");
}

function obtenerFechaInput(valor?: string | null) {
  if (!valor) return "";

  const fecha = new Date(valor);

  if (isNaN(fecha.getTime())) return "";

  return fecha.toISOString().split("T")[0];
}

function obtenerNombreContenedor(contenedor: Contenedor) {
  return (
    contenedor.numero_contenedor ||
    contenedor.numero ||
    contenedor.nombre ||
    contenedor.codigo ||
    contenedor.id
  );
}

export default function ReportesPage() {
  const [guias, setGuias] = useState<Guia[]>([]);
  const [contenedores, setContenedores] = useState<Contenedor[]>([]);

  const [contenedorSeleccionado, setContenedorSeleccionado] =
    useState("");

  const [fechaDesde, setFechaDesde] = useState("");

  const [fechaHasta, setFechaHasta] = useState("");

  const [loading, setLoading] = useState(true);

  const [errorCarga, setErrorCarga] = useState("");

  useEffect(() => {
    cargarDatos();
  }, []);

  async function cargarDatos() {
    setLoading(true);
    setErrorCarga("");

    const {
      data: guiasData,
      error: guiasError,
    } = await supabase
      .from("hce_guias")
      .select("*");

    if (guiasError) {
      console.error(
        "ERROR CARGANDO GUÍAS HCE:",
        guiasError
      );

      setErrorCarga(
        `Error cargando guías HCE: ${guiasError.message}`
      );

      setLoading(false);
      return;
    }

    const guiasHCE: Guia[] = guiasData || [];

    /*
      HCE no utiliza las tablas antiguas de DG Cargo
      para este reporte.

      Los contenedores se obtienen directamente de las
      guías HCE, usando únicamente los datos que ya
      existen en hce_guias.
    */
    const contenedoresHCE: Contenedor[] = [];
    const vistos = new Set<string>();

    for (const guia of guiasHCE) {
      const identificador =
        guia.numero_contenedor ||
        guia.contenedor ||
        guia.contenedor_id;

      if (!identificador) continue;

      const clave = String(identificador);

      if (vistos.has(clave)) continue;

      vistos.add(clave);

      contenedoresHCE.push({
        id: clave,
        numero: clave,
        numero_contenedor: clave,
      });
    }

    setGuias(guiasHCE);
    setContenedores(contenedoresHCE);
    setLoading(false);
  }

  const guiasFiltradas = useMemo(() => {
    return guias.filter((guia) => {
      /*
        ============================
        FILTRO POR CONTENEDOR
        ============================
      */

      if (contenedorSeleccionado) {
        const coincideContenedor =
          guia.contenedor_id ===
            contenedorSeleccionado ||
          guia.contenedor ===
            contenedorSeleccionado ||
          guia.numero_contenedor ===
            contenedorSeleccionado;

        if (!coincideContenedor) {
          return false;
        }
      }

      /*
        ============================
        OBTENER FECHA DE LA GUÍA
        ============================
      */

      const fechaGuia =
        guia.fecha ||
        guia.created_at;

      if (!fechaGuia) {
        return !fechaDesde && !fechaHasta;
      }

      const fecha =
        new Date(fechaGuia);

      if (
        isNaN(fecha.getTime())
      ) {
        return true;
      }

      const fechaSolo =
        fecha.toISOString()
          .split("T")[0];

      /*
        ============================
        DESDE
        ============================
      */

      if (
        fechaDesde &&
        fechaSolo < fechaDesde
      ) {
        return false;
      }

      /*
        ============================
        HASTA
        ============================
      */

      if (
        fechaHasta &&
        fechaSolo > fechaHasta
      ) {
        return false;
      }

      return true;
    });
  }, [
    guias,
    contenedorSeleccionado,
    fechaDesde,
    fechaHasta,
  ]);

  const totalGuias =
    guiasFiltradas.length;

  const totalCajas =
    guiasFiltradas.reduce(
      (total, guia) =>
        total +
        (Number(guia.cajas) || 0),
      0
    );

  const contenedorActual =
    contenedores.find(
      (contenedor) =>
        contenedor.id ===
          contenedorSeleccionado ||
        obtenerNombreContenedor(
          contenedor
        ) === contenedorSeleccionado
    );

  function limpiarFiltros() {
    setContenedorSeleccionado("");
    setFechaDesde("");
    setFechaHasta("");
  }

  async function eliminarGuia(guia: Guia) {
    const numero = guia.numero_guia || guia.id || "SIN NÚMERO";

    const confirmar = window.confirm(
      `¿Seguro que deseas eliminar la guía ${numero}?\n\nTambién se eliminarán las cajas asociadas a esta guía.`
    );

    if (!confirmar) return;

    try {
      const { error: errorCajas } = await supabase
        .from("hce_cajas")
        .delete()
        .eq("guia_id", guia.id);

      if (errorCajas) {
        throw errorCajas;
      }

      const { error } = await supabase
        .from("hce_guias")
        .delete()
        .eq("id", guia.id);

      if (error) {
        throw error;
      }

      setGuias((actuales) =>
        actuales.filter(
          (item) => String(item.id) !== String(guia.id)
        )
      );

      alert("Guía eliminada correctamente.");
    } catch (error: any) {
      console.error("ERROR ELIMINANDO GUÍA HCE:", error);
      alert(
        "No se pudo eliminar la guía: " +
          (error?.message || "Error desconocido")
      );
    }
  }

  async function eliminarTodo() {
    if (guias.length === 0) {
      alert("No hay guías HCE para eliminar.");
      return;
    }

    const confirmar = window.confirm(
      `⚠️ ATENCIÓN\n\nSe eliminarán TODAS las guías HCE (${guias.length}) y todas sus cajas asociadas.\n\nEsta acción no se puede deshacer.\n\n¿Deseas continuar?`
    );

    if (!confirmar) return;

    try {
      const { error: errorCajas } = await supabase
        .from("hce_cajas")
        .delete()
        .not("id", "is", null);

      if (errorCajas) {
        throw errorCajas;
      }

      const { error: errorGuias } = await supabase
        .from("hce_guias")
        .delete()
        .not("id", "is", null);

      if (errorGuias) {
        throw errorGuias;
      }

      setGuias([]);
      setContenedores([]);
      limpiarFiltros();

      alert("Todas las guías HCE fueron eliminadas correctamente.");
    } catch (error: any) {
      console.error("ERROR ELIMINANDO TODAS LAS GUÍAS HCE:", error);
      alert(
        "No se pudieron eliminar todas las guías: " +
          (error?.message || "Error desconocido")
      );
      await cargarDatos();
    }
  }

  function generarPDF() {
    if (guiasFiltradas.length === 0) {
      alert(
        "No hay guías para generar el reporte."
      );

      return;
    }

    const nombreContenedor =
      contenedorActual
        ? obtenerNombreContenedor(
            contenedorActual
          )
        : contenedorSeleccionado ||
          "TODOS LOS CONTENEDORES";

    const ventana =
      window.open(
        "",
        "_blank",
        "width=1200,height=900"
      );

    if (!ventana) {
      alert(
        "El navegador bloqueó la ventana del reporte. Permite las ventanas emergentes e inténtalo nuevamente."
      );

      return;
    }

    const filas = guiasFiltradas
      .map((guia, index) => {
        const numeroGuia =
          guia.numero_guia ||
          guia.id ||
          "";

        const cliente =
          guia.cliente ||
          "";

        const ciudad =
          guia.ciudad ||
          "";

        const direccion =
          guia.direccion ||
          "";

        const telefono =
          guia.telefono ||
          "";

        const correo =
          guia.correo ||
          "";

        const cajas =
          guia.cajas ?? 0;

        const estado =
          guia.estado ||
          "";

        const fecha =
          obtenerFecha(
            guia.fecha ||
              guia.created_at
          );

        return `
          <tr>
            <td>${index + 1}</td>
            <td><strong>${numeroGuia}</strong></td>
            <td>${cliente}</td>
            <td>${telefono}</td>
            <td>${correo}</td>
            <td>${direccion}</td>
            <td>${ciudad}</td>
            <td style="text-align:center">${cajas}</td>
            <td>${estado}</td>
            <td>${fecha}</td>
          </tr>
        `;
      })
      .join("");

    ventana.document.write(`
      <!DOCTYPE html>

      <html lang="es">

        <head>

          <meta charset="UTF-8" />

          <title>
            Reporte Honduras Cargo Express
          </title>

          <style>

            * {
              box-sizing: border-box;
            }

            body {
              font-family:
                Arial,
                Helvetica,
                sans-serif;

              margin: 0;

              padding: 35px;

              color: #111;
            }

            .header {
              border-bottom:
                3px solid #f97316;

              padding-bottom:
                20px;

              margin-bottom:
                25px;
            }

            h1 {
              margin: 0;

              font-size:
                30px;

              color:
                #111827;
            }

            h2 {
              margin-top:
                8px;

              color:
                #f97316;
            }

            .empresa {
              font-size:
                18px;

              font-weight:
                bold;
            }

            .informacion {
              display:
                grid;

              grid-template-columns:
                repeat(2, 1fr);

              gap:
                15px;

              margin-bottom:
                25px;

              background:
                #f3f4f6;

              padding:
                20px;

              border-radius:
                10px;
            }

            .info strong {
              display:
                block;

              margin-bottom:
                5px;
            }

            .totales {
              display:
                flex;

              gap:
                20px;

              margin-bottom:
                25px;
            }

            .total {
              padding:
                18px;

              border:
                1px solid #ddd;

              border-radius:
                10px;

              min-width:
                200px;
            }

            .numero {
              font-size:
                28px;

              font-weight:
                bold;

              color:
                #f97316;

              margin-top:
                5px;
            }

            table {
              width:
                100%;

              border-collapse:
                collapse;

              font-size:
                11px;
            }

            th {
              background:
                #111827;

              color:
                white;

              text-align:
                left;
            }

            th,
            td {
              border:
                1px solid #d1d5db;

              padding:
                8px;

              vertical-align:
                top;
            }

            tr:nth-child(even) {
              background:
                #f9fafb;
            }

            .footer {
              margin-top:
                30px;

              border-top:
                1px solid #ddd;

              padding-top:
                15px;

              font-size:
                12px;

              color:
                #666;
            }

            @media print {

              body {
                padding:
                  15px;
              }

              .no-print {
                display:
                  none;
              }

              @page {
                size:
                  landscape;

                margin:
                  10mm;
              }

            }

          </style>

        </head>

        <body>

          <div class="header">

            <div class="empresa">
              HONDURAS CARGO EXPRESS
            </div>

            <h1>
              REPORTE DE CONTENEDOR
            </h1>

          </div>


          <div class="informacion">

            <div class="info">

              <strong>
                Contenedor
              </strong>

              ${nombreContenedor}

            </div>


            <div class="info">

              <strong>
                Fecha de salida
              </strong>

              ${
                obtenerFecha(
                  contenedorActual?.fecha_salida
                ) || "No registrada"
              }

            </div>


            <div class="info">

              <strong>
                Fecha desde
              </strong>

              ${
                fechaDesde
                  ? obtenerFecha(fechaDesde)
                  : "Sin límite"
              }

            </div>


            <div class="info">

              <strong>
                Fecha hasta
              </strong>

              ${
                fechaHasta
                  ? obtenerFecha(fechaHasta)
                  : "Sin límite"
              }

            </div>

          </div>


          <div class="totales">

            <div class="total">

              Total de guías

              <div class="numero">
                ${totalGuias}
              </div>

            </div>


            <div class="total">

              Total de cajas

              <div class="numero">
                ${totalCajas}
              </div>

            </div>

          </div>


          <h2>
            Detalle de guías
          </h2>


          <table>

            <thead>

              <tr>

                <th>#</th>

                <th>Guía</th>

                <th>Cliente</th>

                <th>Teléfono</th>

                <th>Correo</th>

                <th>Dirección</th>

                <th>Ciudad</th>

                <th>Cajas</th>

                <th>Estado</th>

                <th>Fecha</th>

              </tr>

            </thead>


            <tbody>

              ${filas}

            </tbody>

          </table>


          <div class="footer">

            Reporte generado por
            Honduras Cargo Express

            <br />

            Fecha de generación:
            ${new Date().toLocaleString(
              "es-HN"
            )}

          </div>


          <script>

            window.onload = function () {

              setTimeout(function () {

                window.print();

              }, 500);

            };

          </script>

        </body>

      </html>
    `);

    ventana.document.close();
  }

  if (loading) {
    return (
      <main className="min-h-screen bg-[#020817] p-10 text-white">
        Cargando reportes...
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-[#020817] p-10 text-white">

      {/* BOTÓN INICIO */}

      <div className="mb-8">

        <Link
          href="/dashboard"
          className="inline-flex items-center gap-2 rounded-xl border border-slate-700 bg-slate-800 px-6 py-3 text-lg font-semibold transition hover:bg-slate-700"
        >
          🏠 Inicio
        </Link>

      </div>


      {/* ENCABEZADO */}

      <div className="mb-10">

        <h1 className="text-5xl font-bold">
          📊 Reportes
        </h1>

        <p className="mt-2 text-xl text-slate-400">
          Reporte de guías y contenedores HCE
        </p>

      </div>


      {/* ERROR */}

      {errorCarga && (

        <div className="mb-6 rounded-xl border border-red-500 bg-red-950 p-5 text-red-200">

          {errorCarga}

        </div>

      )}


      {/* FILTROS */}

      <div className="mb-8 rounded-3xl border border-slate-800 bg-slate-900 p-8">

        <h2 className="mb-8 text-3xl font-bold">
          🔎 Generar reporte
        </h2>


        <div className="grid grid-cols-1 gap-6 md:grid-cols-3">

          {/* CONTENEDOR */}

          <div>

            <label className="mb-2 block text-slate-400">
              Contenedor
            </label>

            <select
              value={contenedorSeleccionado}

              onChange={(event) =>
                setContenedorSeleccionado(
                  event.target.value
                )
              }

              className="w-full rounded-xl border border-slate-700 bg-slate-800 px-5 py-4 text-white outline-none focus:border-orange-500"
            >

              <option value="">
                Todos los contenedores
              </option>

              {contenedores.map(
                (contenedor) => (

                  <option
                    key={contenedor.id}

                    value={contenedor.id}
                  >
                    {obtenerNombreContenedor(
                      contenedor
                    )}
                  </option>

                )
              )}

            </select>

          </div>


          {/* FECHA DESDE */}

          <div>

            <label className="mb-2 block text-slate-400">
              Fecha desde
            </label>

            <input
              type="date"

              value={fechaDesde}

              onChange={(event) =>
                setFechaDesde(
                  event.target.value
                )
              }

              className="w-full rounded-xl border border-slate-700 bg-slate-800 px-5 py-4 text-white outline-none focus:border-orange-500"
            />

          </div>


          {/* FECHA HASTA */}

          <div>

            <label className="mb-2 block text-slate-400">
              Fecha hasta
            </label>

            <input
              type="date"

              value={fechaHasta}

              onChange={(event) =>
                setFechaHasta(
                  event.target.value
                )
              }

              className="w-full rounded-xl border border-slate-700 bg-slate-800 px-5 py-4 text-white outline-none focus:border-orange-500"
            />

          </div>

        </div>


        {/* BOTONES */}

        <div className="mt-8 flex flex-wrap gap-4">

          <button
            onClick={generarPDF}

            className="rounded-xl bg-orange-500 px-8 py-4 text-lg font-bold text-white transition hover:bg-orange-600"
          >
            📄 Generar / Descargar PDF
          </button>


          <button
            onClick={limpiarFiltros}

            className="rounded-xl bg-slate-700 px-8 py-4 text-lg font-bold text-white transition hover:bg-slate-600"
          >
            🧹 Limpiar filtros
          </button>


          <button
            onClick={eliminarTodo}

            className="rounded-xl bg-red-600 px-8 py-4 text-lg font-bold text-white transition hover:bg-red-700"
          >
            🗑️ Borrar todo HCE
          </button>

        </div>

      </div>


      {/* RESUMEN */}

      <div className="mb-8 grid grid-cols-1 gap-6 md:grid-cols-2">

        <div className="rounded-2xl border border-blue-900 bg-slate-900 p-6">

          <p className="text-slate-400">
            📦 Total de guías
          </p>

          <h2 className="mt-3 text-5xl font-bold text-blue-400">
            {totalGuias}
          </h2>

        </div>


        <div className="rounded-2xl border border-green-900 bg-slate-900 p-6">

          <p className="text-slate-400">
            📦 Total de cajas
          </p>

          <h2 className="mt-3 text-5xl font-bold text-green-400">
            {totalCajas}
          </h2>

        </div>

      </div>


      {/* TABLA */}

      <div className="overflow-hidden rounded-3xl border border-slate-700 bg-slate-900">

        <div className="overflow-x-auto">

          <table className="w-full">

            <thead className="bg-slate-800">

              <tr>

                <th className="px-5 py-5 text-left">
                  #
                </th>

                <th className="px-5 py-5 text-left">
                  Guía
                </th>

                <th className="px-5 py-5 text-left">
                  Cliente
                </th>

                <th className="px-5 py-5 text-left">
                  Ciudad
                </th>

                <th className="px-5 py-5 text-center">
                  Cajas
                </th>

                <th className="px-5 py-5 text-left">
                  Estado
                </th>

                <th className="px-5 py-5 text-left">
                  Fecha
                </th>

                <th className="px-5 py-5 text-center">
                  Acción
                </th>

              </tr>

            </thead>


            <tbody>

              {guiasFiltradas.map(
                (guia, index) => (

                  <tr
                    key={guia.id}

                    className="border-t border-slate-800 hover:bg-slate-800/50"
                  >

                    <td className="px-5 py-5">
                      {index + 1}
                    </td>


                    <td className="px-5 py-5 font-bold text-orange-400">
                      {guia.numero_guia}
                    </td>


                    <td className="px-5 py-5">
                      {guia.cliente}
                    </td>


                    <td className="px-5 py-5">
                      {guia.ciudad}
                    </td>


                    <td className="px-5 py-5 text-center">
                      {guia.cajas || 0}
                    </td>


                    <td className="px-5 py-5">
                      {guia.estado}
                    </td>


                    <td className="px-5 py-5">
                      {obtenerFecha(
                        guia.fecha ||
                        guia.created_at
                      )}
                    </td>

                    <td className="px-5 py-5 text-center">
                      <button
                        type="button"
                        onClick={() => eliminarGuia(guia)}
                        className="rounded-lg bg-red-600 px-4 py-2 font-bold text-white transition hover:bg-red-700"
                      >
                        🗑️ Borrar
                      </button>
                    </td>

                  </tr>

                )
              )}


              {guiasFiltradas.length === 0 && (

                <tr>

                  <td
                    colSpan={8}

                    className="px-5 py-16 text-center text-xl text-slate-400"
                  >
                    No hay guías para los filtros seleccionados.
                  </td>

                </tr>

              )}

            </tbody>

          </table>

        </div>

      </div>

    </main>
  );
}