﻿"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { supabase } from "@/lib/supabase";

type Guia = {
  id?: string | number;
  estado?: string;
  fecha?: string;
  created_at?: string;
  [key: string]: any;
};

type DashboardStats = {
  guiasHoy: number;
  guiasMes: number;
  totalGuias: number;
  totalCajas: number;
  recibidas: number;
  entregadas: number;
};

const ESTADO_RECIBIDA = [
  "Recibida",
  "Recibida en bodega",
];

function obtenerFechaGuia(guia: Guia) {
  return guia.created_at || guia.fecha || "";
}

function esMismaFechaHoy(fechaTexto: string) {
  if (!fechaTexto) return false;

  const fecha = new Date(fechaTexto);

  if (Number.isNaN(fecha.getTime())) return false;

  const ahora = new Date();

  return (
    fecha.getFullYear() === ahora.getFullYear() &&
    fecha.getMonth() === ahora.getMonth() &&
    fecha.getDate() === ahora.getDate()
  );
}

function esMismoMes(fechaTexto: string) {
  if (!fechaTexto) return false;

  const fecha = new Date(fechaTexto);

  if (Number.isNaN(fecha.getTime())) return false;

  const ahora = new Date();

  return (
    fecha.getFullYear() === ahora.getFullYear() &&
    fecha.getMonth() === ahora.getMonth()
  );
}

function esEstadoRecibida(estado?: string) {
  const estadoNormalizado = (estado || "")
    .trim()
    .toLowerCase();

  return ESTADO_RECIBIDA.some(
    (item) => item.toLowerCase() === estadoNormalizado
  );
}

function esEstadoEntregada(estado?: string) {
  return (
    (estado || "").trim().toLowerCase() === "entregada"
  );
}

export default function DashboardPage() {
  const [stats, setStats] = useState<DashboardStats>({
    guiasHoy: 0,
    guiasMes: 0,
    totalGuias: 0,
    totalCajas: 0,
    recibidas: 0,
    entregadas: 0,
  });

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    cargarDashboard();
  }, []);

  async function cargarDashboard() {
    try {
      setLoading(true);
      setError("");

      const {
        data: guias,
        error: errorGuias,
      } = await supabase
        .from("hce_guias")
        .select("*");

      if (errorGuias) {
        console.error(
          "ERROR CARGANDO HCE_GUIAS:",
          errorGuias
        );

        throw new Error(
          errorGuias.message ||
            "No se pudieron cargar las guías."
        );
      }

      const listaGuias = (guias || []) as Guia[];

      const {
        data: cajas,
        error: errorCajas,
      } = await supabase
        .from("hce_cajas")
        .select("id");

      if (errorCajas) {
        console.error(
          "ERROR CARGANDO HCE_CAJAS:",
          errorCajas
        );

        throw new Error(
          errorCajas.message ||
            "No se pudieron cargar las cajas."
        );
      }

      const guiasHoy = listaGuias.filter((guia) =>
        esMismaFechaHoy(obtenerFechaGuia(guia))
      ).length;

      const guiasMes = listaGuias.filter((guia) =>
        esMismoMes(obtenerFechaGuia(guia))
      ).length;

      const recibidas = listaGuias.filter((guia) =>
        esEstadoRecibida(guia.estado)
      ).length;

      const entregadas = listaGuias.filter((guia) =>
        esEstadoEntregada(guia.estado)
      ).length;

      setStats({
        guiasHoy,
        guiasMes,
        totalGuias: listaGuias.length,
        totalCajas: (cajas || []).length,
        recibidas,
        entregadas,
      });
    } catch (error: any) {
      console.error(
        "ERROR GENERAL DASHBOARD:",
        error
      );

      setError(
        error?.message ||
          "No fue posible cargar el Dashboard."
      );
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="min-h-screen bg-[#07101f] text-white">

      <div className="flex min-h-screen">

        {/* =====================================================
            SIDEBAR PC
        ===================================================== */}

        <aside className="hidden w-[285px] shrink-0 border-r border-slate-800/80 bg-[#0a1425] lg:flex lg:flex-col">

          {/* LOGO */}

          <div className="border-b border-slate-800/80 px-6 py-7">

            <div className="flex items-center gap-3">

              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-orange-500 text-2xl shadow-lg shadow-orange-500/20">
                🚚
              </div>

              <div>
                <div className="text-xl font-black tracking-tight text-white">
                  Honduras Cargo
                </div>

                <div className="mt-0.5 text-xs font-bold uppercase tracking-[0.25em] text-orange-500">
                  Express
                </div>
              </div>

            </div>

          </div>

          {/* MENÚ PC */}

          <nav className="flex-1 overflow-y-auto px-4 py-6">

            <SidebarLink
              icon="▦"
              text="Dashboard"
              href="/dashboard"
              activo
            />

            <SidebarLink
              icon="📦"
              text="Guías"
              href="/guias"
            />

            <SidebarLink
              icon="👥"
              text="Clientes"
              href="/clientes"
            />

            <SidebarLink
              icon="🧾"
              text="Recibos"
              href="/recibos"
            />

            <SidebarLink
              icon="🚚"
              text="Recolectores"
              href="/recolectores"
            />

            <SidebarLink
              icon="📷"
              text="Escanear"
              href="/escaneo"
            />

            <SidebarLink
              icon="📍"
              text="Rastreo"
              href="/rastreo"
            />

            <SidebarLink
              icon="🚢"
              text="Contenedores"
              href="/contenedores"
            />

            <SidebarLink
              icon="💰"
              text="Pagos"
              href="/pagos"
            />

            <SidebarLink
              icon="📊"
              text="Reportes"
              href="/reportes"
            />

          </nav>

          {/* PARTE INFERIOR */}

          <div className="border-t border-slate-800/80 p-4">

            <SidebarLink
              icon="⚙️"
              text="Configuración"
              href="/configuracion"
            />

            <div className="mt-4 rounded-2xl border border-slate-700/70 bg-[#121f34] p-4">

              <div className="flex items-center gap-3">

                <div className="flex h-10 w-10 items-center justify-center rounded-full bg-orange-500 font-black text-white">
                  HC
                </div>

                <div className="min-w-0">

                  <p className="truncate text-sm font-bold text-white">
                    Honduras Cargo
                  </p>

                  <p className="text-xs text-slate-400">
                    Sistema de gestión
                  </p>

                </div>

              </div>

            </div>

          </div>

        </aside>

        {/* =====================================================
            CONTENIDO PRINCIPAL
        ===================================================== */}

        <section className="min-w-0 flex-1">

          {/* BARRA SUPERIOR */}

          <header className="border-b border-slate-800/80 bg-[#091425]/90 px-4 py-3 md:px-8 md:py-4">

            <div className="mx-auto flex max-w-[1500px] items-center justify-between gap-4">

              <div className="flex items-center gap-3 lg:hidden">

                <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-orange-500 text-xl">
                  🚚
                </div>

                <div>
                  <div className="font-black text-white">
                    Honduras Cargo
                  </div>

                  <div className="text-[10px] font-bold uppercase tracking-[0.2em] text-orange-500">
                    Express
                  </div>
                </div>

              </div>

              <div className="hidden lg:block">
                <p className="text-sm font-medium text-slate-400">
                  Panel de administración
                </p>
              </div>

              <button
                type="button"
                onClick={async () => {
                  try {
                    await fetch(
                      "/cargoerp/api/logout",
                      {
                        method: "POST",
                        credentials: "include",
                      }
                    );
                  } catch {}

                  window.location.href =
                    "/cargoerp/";
                }}
                className="rounded-xl border border-red-500/30 bg-red-600 px-4 py-2.5 text-sm font-bold text-white transition hover:bg-red-700 md:px-5"
              >
                🚪
                <span className="ml-2">
                  Cerrar sesión
                </span>
              </button>

            </div>

          </header>

          {/* =====================================================
              MENÚ MÓVIL COMPACTO
          ===================================================== */}

          <nav
            className="border-b border-slate-800/80 bg-[#091425] px-1.5 py-1 lg:hidden"
            style={{
              scrollbarWidth: "none",
              WebkitOverflowScrolling: "touch",
            }}
          >

            <div className="flex gap-0.5 overflow-x-auto">

              <MobileNavItem
                icon="▦"
                text="Inicio"
                href="/dashboard"
              />

              <MobileNavItem
                icon="📦"
                text="Nueva guía"
                href="/guias/nueva"
              />

              <MobileNavItem
                icon="👥"
                text="Clientes"
                href="/clientes"
              />

              <MobileNavItem
                icon="🧾"
                text="Recibos"
                href="/recibos"
              />

              <MobileNavItem
                icon="📷"
                text="Escanear"
                href="/escaneo"
              />

              <MobileNavItem
                icon="📍"
                text="Rastreo"
                href="/rastreo"
              />

              <MobileNavItem
                icon="🚢"
                text="Contenedores"
                href="/contenedores"
              />

              <MobileNavItem
                icon="💰"
                text="Pagos"
                href="/pagos"
              />

              <MobileNavItem
                icon="📊"
                text="Reportes"
                href="/reportes"
              />

              <MobileNavItem
                icon="🚚"
                text="Recolectores"
                href="/recolectores"
              />

            </div>

          </nav>

          {/* =====================================================
              CONTENIDO
          ===================================================== */}

          <div className="mx-auto max-w-[1500px] px-5 pb-12 pt-7 md:px-8 lg:pt-9">

            {/* ENCABEZADO */}

            <div className="mb-8">

              <div className="flex flex-col justify-between gap-5 md:flex-row md:items-end">

                <div>

                  <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-orange-500/20 bg-orange-500/10 px-3 py-1.5 text-xs font-bold uppercase tracking-wider text-orange-400">

                    <span className="h-2 w-2 rounded-full bg-orange-500" />

                    Sistema activo

                  </div>

                  <h1 className="text-3xl font-black tracking-tight text-white md:text-5xl">
                    Dashboard
                  </h1>

                  <p className="mt-2 max-w-2xl text-sm leading-6 text-slate-400 md:text-base">
                    Resumen general de Honduras Cargo Express
                  </p>

                </div>

                <Link
                  href="/guias/nueva"
                  className="inline-flex items-center justify-center gap-2 rounded-xl bg-orange-500 px-5 py-3.5 font-black text-white shadow-lg shadow-orange-500/20 transition hover:-translate-y-0.5 hover:bg-orange-600"
                >
                  <span className="text-lg">
                    ＋
                  </span>

                  Nueva guía

                </Link>

              </div>

            </div>

            {/* ERROR */}

            {error && (
              <div className="mb-6 rounded-2xl border border-red-500/40 bg-red-500/10 p-4 text-sm font-medium text-red-300">
                ❌ {error}
              </div>
            )}

            {/* =====================================================
                ESTADÍSTICAS
            ===================================================== */}

            <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">

              <DashboardCard
                href="/guias?filtro=hoy"
                titulo="Guías hoy"
                numero={
                  loading
                    ? "..."
                    : stats.guiasHoy
                }
                descripcion="Registradas durante el día"
                icono="📅"
              />

              <DashboardCard
                href="/guias?filtro=mes"
                titulo="Guías del mes"
                numero={
                  loading
                    ? "..."
                    : stats.guiasMes
                }
                descripcion="Registradas este mes"
                icono="📦"
              />

              <DashboardCard
                href="/guias?filtro=total"
                titulo="Total de guías"
                numero={
                  loading
                    ? "..."
                    : stats.totalGuias
                }
                descripcion="Guías registradas"
                icono="🧾"
              />

              <DashboardCard
                href="/contenedores?filtro=cajas"
                titulo="Total de cajas"
                numero={
                  loading
                    ? "..."
                    : stats.totalCajas
                }
                descripcion="Cajas registradas"
                icono="📦"
              />

            </div>

            {/* =====================================================
                ESTADOS
            ===================================================== */}

            <div className="mt-6 grid gap-4 sm:grid-cols-2">

              <StatusCard
                href="/guias?estado=recibida"
                titulo="Guías recibidas"
                numero={
                  loading
                    ? "..."
                    : stats.recibidas
                }
                descripcion="Pendientes de entrega"
                icono="↓"
              />

              <StatusCard
                href="/guias?estado=entregada"
                titulo="Guías entregadas"
                numero={
                  loading
                    ? "..."
                    : stats.entregadas
                }
                descripcion="Entregas completadas"
                icono="✓"
              />

            </div>

            {/* =====================================================
                INFORMACIÓN
            ===================================================== */}

            <div className="mt-8 overflow-hidden rounded-3xl border border-slate-800 bg-[#101d31]">

              <div className="flex flex-col gap-5 p-6 md:flex-row md:items-center md:justify-between md:p-8">

                <div>

                  <div className="mb-2 flex items-center gap-2 text-orange-400">

                    <span className="text-xl">
                      🚚
                    </span>

                    <span className="text-xs font-black uppercase tracking-[0.2em]">
                      Honduras Cargo Express
                    </span>

                  </div>

                  <h2 className="text-2xl font-black text-white">
                    Sistema de gestión
                  </h2>

                  <p className="mt-2 max-w-2xl text-sm leading-6 text-slate-400">
                    Administra guías, clientes, recolectores,
                    rastreo, contenedores, pagos y reportes
                    desde un solo lugar.
                  </p>

                </div>

                <Link
                  href="/guias"
                  className="inline-flex shrink-0 items-center justify-center rounded-xl border border-slate-600 bg-slate-800 px-5 py-3 font-bold text-white transition hover:border-orange-500 hover:bg-slate-700"
                >
                  Ver guías →
                </Link>

              </div>

              <div className="border-t border-slate-800 bg-[#0c1729] px-6 py-4 md:px-8">

                <div className="flex flex-col gap-2 text-xs text-slate-500 sm:flex-row sm:items-center sm:justify-between">

                  <span>
                    Honduras Cargo Express
                  </span>

                  <span>
                    Panel administrativo
                  </span>

                </div>

              </div>

            </div>

          </div>

        </section>

      </div>

    </main>
  );
}

/* =============================================================
   MENÚ MÓVIL
============================================================= */

function MobileNavItem({
  icon,
  text,
  href,
}: {
  icon: string;
  text: string;
  href: string;
}) {
  return (
    <Link
      href={href}
      className="flex min-w-[68px] shrink-0 flex-col items-center justify-center rounded-lg px-1.5 py-1.5 text-[9px] font-bold text-slate-400 transition hover:bg-[#142239] hover:text-white active:scale-95"
    >

      <span className="text-[17px] leading-none">
        {icon}
      </span>

      <span className="mt-0.5 whitespace-nowrap">
        {text}
      </span>

    </Link>
  );
}

/* =============================================================
   TARJETA PRINCIPAL
============================================================= */

function DashboardCard({
  href,
  titulo,
  numero,
  descripcion,
  icono,
}: {
  href: string;
  titulo: string;
  numero: number | string;
  descripcion: string;
  icono: string;
}) {
  return (
    <Link
      href={href}
      className="group relative overflow-hidden rounded-2xl border border-slate-800 bg-[#111e32] p-5 transition duration-200 hover:-translate-y-1 hover:border-orange-500/60 hover:bg-[#15243b] hover:shadow-xl hover:shadow-black/20 md:p-6"
    >

      <div className="absolute -right-10 -top-10 h-28 w-28 rounded-full bg-orange-500/5 transition group-hover:bg-orange-500/10" />

      <div className="relative flex items-start justify-between gap-4">

        <div className="min-w-0">

          <p className="text-sm font-bold text-slate-400">
            {titulo}
          </p>

          <p className="mt-3 text-4xl font-black tracking-tight text-white md:text-5xl">
            {numero}
          </p>

        </div>

        <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-slate-700 bg-[#1b2b44] text-xl transition group-hover:border-orange-500/30 group-hover:bg-orange-500 group-hover:text-white">
          {icono}
        </div>

      </div>

      <div className="relative mt-5 border-t border-slate-800 pt-4">

        <p className="text-xs font-medium text-slate-500">
          {descripcion}
        </p>

        <p className="mt-2 text-xs font-black uppercase tracking-wider text-orange-500">
          Ver información →
        </p>

      </div>

    </Link>
  );
}

/* =============================================================
   TARJETA DE ESTADO
============================================================= */

function StatusCard({
  href,
  titulo,
  numero,
  descripcion,
  icono,
}: {
  href: string;
  titulo: string;
  numero: number | string;
  descripcion: string;
  icono: string;
}) {
  return (
    <Link
      href={href}
      className="group flex items-center justify-between gap-5 rounded-2xl border border-slate-800 bg-[#111e32] p-5 transition hover:-translate-y-0.5 hover:border-orange-500/50 hover:bg-[#15243b] md:p-6"
    >

      <div className="flex min-w-0 items-center gap-4">

        <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl bg-[#1b2b44] text-xl text-orange-400 transition group-hover:bg-orange-500 group-hover:text-white">
          {icono}
        </div>

        <div className="min-w-0">

          <p className="font-black text-white">
            {titulo}
          </p>

          <p className="mt-1 truncate text-xs text-slate-500">
            {descripcion}
          </p>

        </div>

      </div>

      <div className="shrink-0 text-right">

        <p className="text-3xl font-black text-white">
          {numero}
        </p>

        <p className="mt-1 text-xs font-bold text-orange-500">
          Ver →
        </p>

      </div>

    </Link>
  );
}

/* =============================================================
   SIDEBAR
============================================================= */

function SidebarLink({
  icon,
  text,
  href,
  activo = false,
}: {
  icon: string;
  text: string;
  href: string;
  activo?: boolean;
}) {
  return (
    <Link
      href={href}
      className={`mb-1 flex items-center gap-4 rounded-xl px-4 py-3.5 text-sm font-bold transition ${
        activo
          ? "bg-orange-500 text-white shadow-lg shadow-orange-500/20"
          : "text-slate-300 hover:bg-[#142239] hover:text-white"
      }`}
    >

      <span className="flex w-6 justify-center text-lg">
        {icon}
      </span>

      <span>
        {text}
      </span>

    </Link>
  );
}