"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { supabase } from "../lib/supabase";

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

const estados = [
  {
    value: "Recibida",
    label: "?? Recibida",
  },
  {
    value: "Recolectada",
    label: "?? En Bodega",
  },
  {
    value: "Ingreso en el contenedor",
    label: "?? Ingreso en el contenedor",
  },
  {
    value: "En tránsito",
    label: "?? En tránsito",
  },
  {
    value: "Llegó a Honduras",
    label: "???? Llegó a Honduras",
  },
  {
    value: "En entrega",
    label: "?? Ruta de entrega",
  },
  {
    value: "Entregada",
    label: "? Entregada",
  },
];

export default function GuiasPage() {
  const router = useRouter();

  const [guias, setGuias] = useState<Guia[]>([]);
  const [loading, setLoading] = useState(true);
  const [verificandoSesion, setVerificandoSesion] = useState(true);
  const [errorCarga, setErrorCarga] = useState("");

  useEffect(() => {
    verificarSesion();
  }, []);

  async function verificarSesion() {
    try {
      setVerificandoSesion(true);

      const respuesta = await fetch("/api/sesion", {
        method: "GET",
        cache: "no-store",
      });

      if (!respuesta.ok) {
        router.replace("/login");
        return;
      }

      const data = await respuesta.json();

      if (!data || data.success === false || !data.usuario) {
        router.replace("/login");
        return;
      }

      await cargarGuias();

    } catch (error) {
      console.error(
        "ERROR VERIFICANDO SESIÓN:",
        error
      );

      router.replace("/login");

    } finally {
      setVerificandoSesion(false);
    }
  }

  async function cargarGuias() {
    try {
      console.log("Iniciando carga de guías...");

      setLoading(true);
      setErrorCarga("");

      const { data, error } = await supabase
        .from("hce_guias")
        .select("*");

      if (error) {
        console.error(
          "ERROR CARGANDO GUÍAS:",
          error
        );

        throw new Error(
          error.message ||
            "Error desconocido al cargar las guías."
        );
      }

      console.log(
        "Guías recibidas:",
        data
      );

      const guiasOrdenadas = [
        ...(data || []),
      ].sort(
        (a: Guia, b: Guia) => {
          const fechaA = new Date(
            a.created_at ||
              a.fecha ||
              0
          ).getTime();

          const fechaB = new Date(
            b.created_at ||
              b.fecha ||
              0
          ).getTime();

          return fechaB - fechaA;
        }
      );

      setGuias(guiasOrdenadas);

    } catch (error: any) {

      console.error(
        "ERROR GENERAL AL CARGAR GUÍAS:",
        error
      );

      setErrorCarga(
        error?.message ||
          "No fue posible conectar con la base de datos."
      );

      setGuias([]);

    } finally {

      setLoading(false);

    }
  }

  async function cambiarEstado(
    id: number | string,
    nuevoEstado: string
  ) {
    const estadoAnterior =
      guias.find(
        (guia) => guia.id === id
      )?.estado;

    setGuias((guiasActuales) =>
      guiasActuales.map((guia) =>
        guia.id === id
          ? {
              ...guia,
              estado: nuevoEstado,
            }
          : guia
      )
    );

    try {

      const { error } = await supabase
        .from("hce_guias")
        .update({
          estado: nuevoEstado,
        })
        .eq("id", id);

      if (error) {
        throw error;
      }

    } catch (error: any) {

      console.error(
        "Error actualizando estado:",
        error
      );

      setGuias((guiasActuales) =>
        guiasActuales.map((guia) =>
          guia.id === id
            ? {
                ...guia,
                estado:
                  estadoAnterior ||
                  "Recibida",
              }
            : guia
        )
      );

      alert(
        "No se pudo actualizar el estado: " +
          (
            error?.message ||
            "Error desconocido"
          )
      );
    }
  }

  async function eliminarGuia(
    id: number | string,
    numero: string
  ) {
    const confirmar = window.confirm(
      `¿Seguro que deseas eliminar la guía ${numero}?`
    );

    if (!confirmar) {
      return;
    }

    try {

      const { error: errorCajas } =
        await supabase
          .from("hce_cajas")
          .delete()
          .eq("guia_id", id);

      if (errorCajas) {

        console.warn(
          "No se pudieron eliminar las cajas:",
          errorCajas
        );

        throw errorCajas;
      }

      const { error } =
        await supabase
          .from("hce_guias")
          .delete()
          .eq("id", id);

      if (error) {
        throw error;
      }

      setGuias((guiasActuales) =>
        guiasActuales.filter(
          (guia) =>
            guia.id !== id
        )
      );

      alert(
        "Guía eliminada correctamente."
      );

    } catch (error: any) {

      console.error(
        "Error eliminando guía:",
        error
      );

      alert(
        "No se pudo eliminar la guía: " +
          (
            error?.message ||
            "Error desconocido"
          )
      );
    }
  }

  async function enviarCorreo(
    guia: Guia
  ) {
    try {

      let clienteEncontrado: any = null;

      const telefonoGuia = String(
        guia.telefono || ""
      ).trim();

      const nombreGuia = String(
        guia.cliente || ""
      ).trim();

      if (telefonoGuia) {

        const { data, error } =
          await supabase
            .from("hce_clientes")
            .select("*")
            .eq(
              "telefono",
              telefonoGuia
            );

        if (error) {
          console.error(
            "Error buscando cliente:",
            error
          );
        }

        if (
          data &&
          data.length > 0
        ) {

          clienteEncontrado =
            data.find(
              (cliente: any) =>
                cliente.correo &&
                String(
                  cliente.correo
                ).trim() !== ""
            );
        }
      }

      if (
        !clienteEncontrado &&
        nombreGuia
      ) {

        const { data, error } =
          await supabase
            .from("hce_clientes")
            .select("*");

        if (error) {
          throw error;
        }

        const normalizar = (
          texto: string
        ) =>
          String(texto || "")
            .toLowerCase()
            .trim()
            .replace(/\s+/g, " ");

        const nombreNormalizado =
          normalizar(nombreGuia);

        clienteEncontrado =
          (data || []).find(
            (cliente: any) =>
              normalizar(
                cliente.nombre
              ) === nombreNormalizado &&
              cliente.correo &&
              String(
                cliente.correo
              ).trim() !== ""
          );
      }

      if (
        !clienteEncontrado ||
        !clienteEncontrado.correo
      ) {

        alert(
          `No se encontró un correo registrado para ${
            nombreGuia ||
            "este cliente"
          }.`
        );

        return;
      }

      const correo =
        String(
          clienteEncontrado.correo
        ).trim();

      const nombreCliente =
        clienteEncontrado.nombre ||
        guia.cliente ||
        "Cliente";

      const numeroGuia =
        guia.numero ||
        guia.numero_guia ||
        "Sin número";

      const asunto =
        `Actualización de su envío Honduras Cargo Express - Guía ${numeroGuia}`;

      const mensaje = `Hola ${nombreCliente},

Gracias por utilizar Honduras Cargo Express.

Tenemos una actualización sobre su envío.

?? Número de guía: ${numeroGuia}

?? Destino: ${
  guia.ciudad ||
  "No especificado"
}

?? Estado actual: ${
  guia.estado ||
  "Registrada"
}

Puede utilizar su número de guía para realizar el seguimiento de su envío.

Gracias por confiar en nosotros.

Honduras Cargo Express ??`;

      const gmailUrl =
        "https://mail.google.com/mail/?view=cm" +
        "&fs=1" +
        `&to=${encodeURIComponent(correo)}` +
        `&su=${encodeURIComponent(asunto)}` +
        `&body=${encodeURIComponent(mensaje)}`;

      window.open(
        gmailUrl,
        "_blank"
      );

    } catch (error: any) {

      console.error(
        "Error preparando correo:",
        error
      );

      alert(
        "Ocurrió un error al preparar el correo: " +
          (
            error?.message ||
            "Error desconocido"
          )
      );
    }
  }

  if (verificandoSesion) {
    return (
      <main className="flex min-h-screen items-center justify-center bg-[#020817] text-white">
        <div className="text-center">
          <div className="mb-4 text-5xl">
            ??
          </div>

          <h1 className="text-2xl font-bold">
            Verificando sesión...
          </h1>

          <p className="mt-2 text-slate-400">
            Honduras Cargo Express
          </p>
        </div>
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-[#020817] p-10 text-white">

      <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 text-white transition hover:bg-slate-700"
        >
          ?? Inicio
        </Link>

      </div>

      <div className="mb-10 flex items-center justify-between">

        <div>

          <h1 className="text-5xl font-bold">
            ?? Guías
          </h1>

          <p className="mt-2 text-xl text-slate-400">
            Administración de envíos de Honduras Cargo Express
          </p>

        </div>

        <Link
          href="/guias/nueva"
          className="rounded-2xl bg-orange-500 px-8 py-4 text-lg font-bold text-white transition hover:bg-orange-600"
        >
          + Nueva Guía
        </Link>

      </div>

      {loading && (

        <div className="mb-6 rounded-xl border border-blue-500 bg-blue-950 p-5 text-blue-200">

          <strong>
            Cargando guías...
          </strong>

          <br />

          Conectando con la base de datos.

        </div>

      )}

      {errorCarga && (

        <div className="mb-6 rounded-xl border border-red-500 bg-red-950 p-5 text-red-200">

          <strong>
            Error al cargar las guías:
          </strong>

          <br />

          {errorCarga}

          <br />

          <button
            type="button"
            onClick={cargarGuias}
            className="mt-4 rounded-lg bg-red-600 px-5 py-2 font-bold text-white hover:bg-red-700"
          >
            Reintentar
          </button>

        </div>

      )}

      <div className="overflow-hidden rounded-3xl border border-slate-700 bg-slate-900 shadow-2xl">

        <div className="overflow-x-auto">

          <table className="w-full">

            <thead className="bg-slate-800">

              <tr>

                <th className="px-5 py-5 text-left text-lg">
                  Guía
                </th>

                <th className="px-5 py-5 text-left text-lg">
                  Cliente
                </th>

                <th className="px-5 py-5 text-left text-lg">
                  Ciudad
                </th>

                <th className="px-5 py-5 text-left text-lg">
                  Estado
                </th>

                <th className="px-5 py-5 text-left text-lg">
                  Fecha
                </th>

                <th className="px-5 py-5 text-center text-lg">
                  Acciones
                </th>

              </tr>

            </thead>

            <tbody>

              {guias.map((guia) => {

                const numeroGuia =
                  guia.numero ||
                  guia.numero_guia ||
                  "Sin número";

                return (

                  <tr
                    key={guia.id}
                    className="border-t border-slate-700 transition hover:bg-slate-800/70"
                  >

                    <td className="px-5 py-5 font-bold text-orange-400">
                      {numeroGuia}
                    </td>

                    <td className="px-5 py-5 text-lg">
                      {guia.cliente || "-"}
                    </td>

                    <td className="px-5 py-5 text-lg">
                      {guia.ciudad || "-"}
                    </td>

                    <td className="px-5 py-5">

                      <select
                        value={
                          guia.estado ||
                          "Recibida"
                        }
                        onChange={(event) =>
                          cambiarEstado(
                            guia.id,
                            event.target.value
                          )
                        }
                        className="w-full rounded-2xl border border-slate-600 bg-slate-800 px-5 py-3 text-lg text-white outline-none focus:border-orange-500"
                      >

                        {estados.map(
                          (estado) => (

                            <option
                              key={estado.value}
                              value={estado.value}
                            >
                              {estado.label}
                            </option>

                          )
                        )}

                      </select>

                    </td>

                    <td className="px-5 py-5 text-lg">

                      {guia.fecha
                        ? new Date(
                            guia.fecha
                          ).toLocaleString()
                        : guia.created_at
                        ? new Date(
                            guia.created_at
                          ).toLocaleString()
                        : "-"}

                    </td>

                    <td className="px-5 py-5">

                      <div className="flex justify-center gap-3">

                        <Link
                          href={`/guias/${guia.id}`}
                          className="rounded-xl bg-blue-600 px-4 py-3 hover:bg-blue-700"
                          title="Ver guía"
                        >
                          ??
                        </Link>

                        <Link
                          href={`/guias/${guia.id}/editar`}
                          className="rounded-xl bg-yellow-500 px-4 py-3 hover:bg-yellow-600"
                          title="Editar guía"
                        >
                          ??
                        </Link>

                        <button
                          type="button"
                          onClick={() =>
                            enviarCorreo(guia)
                          }
                          className="rounded-xl bg-green-600 px-4 py-3 hover:bg-green-700"
                          title="Enviar correo"
                        >
                          ??
                        </button>

                        <button
                          type="button"
                          onClick={() =>
                            eliminarGuia(
                              guia.id,
                              numeroGuia
                            )
                          }
                          className="rounded-xl bg-red-600 px-4 py-3 hover:bg-red-700"
                          title="Eliminar guía"
                        >
                          ??
                        </button>

                      </div>

                    </td>

                  </tr>

                );
              })}

              {!loading &&
                guias.length === 0 &&
                !errorCarga && (

                  <tr>

                    <td
                      colSpan={6}
                      className="px-5 py-10 text-center text-xl text-slate-400"
                    >
                      No hay guías registradas.
                    </td>

                  </tr>

                )}

            </tbody>

          </table>

        </div>

      </div>

    </main>
  );
}