"use client";

import { useEffect, useMemo, useState } from "react";
import { supabase } from "@/lib/supabase";
import { getCurrentUser, SessionUser } from "@/lib/session-client";
import PageLayout from "@/components/layout/PageLayout";
import Button from "@/components/ui/Button";
import Input from "@/components/ui/Input";
import Card from "@/components/ui/Card";
import Badge from "@/components/ui/Badge";
import Modal from "@/components/ui/Modal";

type Cliente = {
  id: number;
  nombre: string;
  telefono: string | null;
  correo: string | null;
  ciudad: string | null;
  direccion: string | null;
  total_envios?: number;
  actualizado?: string;
};

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

type Caja = {
  id: number | string;
  guia_id: number | string;
};

function normalizarTelefono(valor?: string | null) {
  if (!valor) return "";
  const digitos = valor.replace(/\D/g, "");

  // Formato hondureño con prefijo 504
  if (digitos.startsWith("504") && digitos.length >= 10) {
    return digitos.slice(3);
  }

  return digitos;
}

function obtenerNumeroGuia(guia: Guia) {
  return guia.numero_guia || guia.numero || `HCE-${guia.id}`;
}

function obtenerFecha(guia: Guia) {
  return guia.fecha || guia.created_at || "";
}

function formatearFecha(fecha: string) {
  if (!fecha) return "-";
  const fechaConvertida = new Date(fecha);
  if (Number.isNaN(fechaConvertida.getTime())) return "-";

  return fechaConvertida.toLocaleString("es-HN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function obtenerVarianteEstado(estado?: string) {
  const e = (estado || "").toUpperCase();
  if (e === "ENTREGADA") return "success";
  if (e === "EN_RUTA") return "orange";
  if (e === "LLEGO_HONDURAS") return "purple";
  if (e === "EN_CONTENEDOR") return "info";
  if (e === "EN_BODEGA") return "warning";
  return "default";
}

export default function ClientesPage() {
  const [clientes, setClientes] = useState<Cliente[]>([]);
  const [busqueda, setBusqueda] = useState("");

  const [nombre, setNombre] = useState("");
  const [telefono, setTelefono] = useState("");
  const [correo, setCorreo] = useState("");
  const [ciudad, setCiudad] = useState("");
  const [direccion, setDireccion] = useState("");

  const [mensaje, setMensaje] = useState("");
  const [guardando, setGuardando] = useState(false);
  const [eliminando, setEliminando] = useState<number | null>(null);
  const [clienteEditando, setClienteEditando] = useState<Cliente | null>(null);

  const [clienteHistorial, setClienteHistorial] = useState<Cliente | null>(null);
  const [guiasHistorial, setGuiasHistorial] = useState<Guia[]>([]);
  const [cajasHistorial, setCajasHistorial] = useState<Caja[]>([]);
  const [cargandoHistorial, setCargandoHistorial] = useState(false);

  const [usuarioSesion, setUsuarioSesion] = useState<SessionUser | null>(null);

  useEffect(() => {
    getCurrentUser().then(setUsuarioSesion).catch(() => setUsuarioSesion(null));
    cargarClientes();
  }, []);

  async function cargarClientes() {
    setMensaje("");
    const { data, error } = await supabase
      .from("hce_clientes")
      .select("*")
      .order("id", { ascending: false });

    if (error) {
      console.error("ERROR AL CARGAR CLIENTES HCE:", error);
      setMensaje("Error al cargar clientes HCE: " + error.message);
      return;
    }

    setClientes((data || []) as Cliente[]);
  }

  async function guardarCliente(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setMensaje("");

    if (!nombre.trim()) {
      setMensaje("El nombre del cliente es obligatorio.");
      return;
    }

    setGuardando(true);

    const datosCliente = {
      nombre: nombre.trim(),
      telefono: telefono.trim() || null,
      correo: correo.trim() || null,
      ciudad: ciudad.trim() || null,
      direccion: direccion.trim() || null,
      actualizado: new Date().toISOString(),
    };

    if (clienteEditando) {
      const { error } = await supabase
        .from("hce_clientes")
        .update(datosCliente)
        .eq("id", clienteEditando.id);

      setGuardando(false);

      if (error) {
        console.error("ERROR AL ACTUALIZAR CLIENTE HCE:", error);
        setMensaje("Error al actualizar el cliente: " + error.message);
        return;
      }

      setMensaje("Cliente actualizado correctamente.");
      limpiarFormulario();
      await cargarClientes();
      return;
    }

    const { error } = await supabase.from("hce_clientes").insert([
      {
        ...datosCliente,
        total_envios: 0,
        creado_por: usuarioSesion?.usuario || null,
      },
    ]);

    setGuardando(false);

    if (error) {
      console.error("ERROR AL GUARDAR CLIENTE HCE:", error);
      setMensaje("Error al guardar el cliente: " + error.message);
      return;
    }

    setMensaje("Cliente guardado correctamente.");
    limpiarFormulario();
    await cargarClientes();
  }

  function editarCliente(cliente: Cliente) {
    setClienteEditando(cliente);
    setNombre(cliente.nombre || "");
    setTelefono(cliente.telefono || "");
    setCorreo(cliente.correo || "");
    setCiudad(cliente.ciudad || "");
    setDireccion(cliente.direccion || "");
    setMensaje("");
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  async function eliminarCliente(cliente: Cliente) {
    const confirmar = window.confirm(`¿Seguro que deseas eliminar a ${cliente.nombre}?`);
    if (!confirmar) return;

    setMensaje("");
    setEliminando(cliente.id);

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

    setEliminando(null);

    if (error) {
      console.error("ERROR AL ELIMINAR CLIENTE HCE:", error);
      setMensaje("No se pudo eliminar el cliente: " + error.message);
      return;
    }

    setMensaje("Cliente eliminado correctamente.");

    if (clienteEditando && clienteEditando.id === cliente.id) {
      limpiarFormulario();
    }

    await cargarClientes();
  }

  function cancelarEdicion() {
    limpiarFormulario();
    setMensaje("");
  }

  function limpiarFormulario() {
    setNombre("");
    setTelefono("");
    setCorreo("");
    setCiudad("");
    setDireccion("");
    setClienteEditando(null);
  }

  async function abrirHistorial(cliente: Cliente) {
    setClienteHistorial(cliente);
    setCargandoHistorial(true);
    setGuiasHistorial([]);
    setCajasHistorial([]);

    try {
      const { data: guiasData, error: guiasError } = await supabase
        .from("hce_guias")
        .select("*")
        .eq("cliente", cliente.nombre)
        .order("id", { ascending: false });

      if (guiasError) {
        console.error("Error cargando historial:", guiasError);
        setGuiasHistorial([]);
      } else {
        const guias = (guiasData || []) as Guia[];
        setGuiasHistorial(guias);

        if (guias.length > 0) {
          const ids = guias.map((g) => g.id);
          const { data: cajasData, error: cajasError } = await supabase
            .from("hce_cajas")
            .select("id, guia_id")
            .in("guia_id", ids);

          if (cajasError) {
            console.warn("Error cargando cajas del historial:", cajasError);
          } else {
            setCajasHistorial((cajasData || []) as Caja[]);
          }
        }
      }
    } finally {
      setCargandoHistorial(false);
    }
  }

  function cerrarHistorial() {
    setClienteHistorial(null);
    setGuiasHistorial([]);
    setCajasHistorial([]);
  }

  const clientesFiltrados = useMemo(() => {
    const termino = busqueda.trim().toLowerCase();
    const telefonoNormalizado = normalizarTelefono(busqueda.trim());

    return clientes.filter((cliente) => {
      if (!termino) return true;

      const coincideNombre = (cliente.nombre || "").toLowerCase().includes(termino);
      const coincideCorreo = (cliente.correo || "").toLowerCase().includes(termino);
      const coincideCiudad = (cliente.ciudad || "").toLowerCase().includes(termino);
      const telefonoCliente = normalizarTelefono(cliente.telefono);
      const coincideTelefono =
        telefonoNormalizado.length > 0 &&
        (telefonoCliente.includes(telefonoNormalizado) ||
          telefonoNormalizado.includes(telefonoCliente));

      return coincideNombre || coincideCorreo || coincideCiudad || coincideTelefono;
    });
  }, [clientes, busqueda]);

  return (
    <PageLayout>
      {/* Encabezado */}
      <section className="mb-4 lg:mb-5">
        <div>
          <h1 className="text-xl font-black text-[var(--text-primary)] lg:text-2xl">
            Clientes
          </h1>
          <p className="mt-0.5 text-xs text-[var(--text-muted)]">
            Administración de clientes de Honduras Cargo Express
          </p>
        </div>
      </section>

      {/* Formulario */}
      <Card className="mb-4" padding="sm">
        <h3 className="mb-3 text-sm font-black text-[var(--text-primary)]">
          {clienteEditando ? "Editar cliente" : "Agregar cliente"}
        </h3>

        {clienteEditando && (
          <div className="mb-3 rounded-lg border border-blue-500/30 bg-blue-500/10 p-2.5">
            <p className="text-xs text-blue-500">
              Editando a: <strong>{clienteEditando.nombre}</strong>
            </p>
          </div>
        )}

        <form onSubmit={guardarCliente}>
          <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
            <Input
              label="Nombre completo *"
              placeholder="Nombre completo"
              value={nombre}
              onChange={(e) => setNombre(e.target.value)}
              required
            />
            <Input
              label="Teléfono"
              placeholder="9999-9999"
              value={telefono}
              onChange={(e) => setTelefono(e.target.value)}
            />
            <Input
              label="Correo electrónico"
              type="email"
              placeholder="correo@ejemplo.com"
              value={correo}
              onChange={(e) => setCorreo(e.target.value)}
            />
            <Input
              label="Ciudad"
              placeholder="Ciudad"
              value={ciudad}
              onChange={(e) => setCiudad(e.target.value)}
            />
            <div className="md:col-span-2">
              <Input
                label="Dirección"
                placeholder="Dirección completa"
                value={direccion}
                onChange={(e) => setDireccion(e.target.value)}
              />
            </div>
          </div>

          <div className="mt-4 flex flex-col gap-2 sm:flex-row">
            <Button type="submit" size="sm" disabled={guardando} className="sm:flex-1">
              {guardando
                ? "Guardando..."
                : clienteEditando
                ? "Guardar cambios"
                : "Guardar cliente"}
            </Button>

            {clienteEditando && (
              <Button type="button" size="sm" variant="ghost" onClick={cancelarEdicion}>
                Cancelar
              </Button>
            )}
          </div>
        </form>

        {mensaje && (
          <div
            className={`mt-4 rounded-lg border p-3 text-xs font-medium ${
              mensaje.includes("correctamente")
                ? "border-green-500/30 bg-green-500/10 text-green-500"
                : "border-red-500/30 bg-red-500/10 text-red-500"
            }`}
          >
            {mensaje}
          </div>
        )}
      </Card>

      {/* Búsqueda */}
      <Card className="mb-4" padding="sm">
        <Input
          placeholder="Buscar por nombre, teléfono, correo o ciudad..."
          value={busqueda}
          onChange={(e) => setBusqueda(e.target.value)}
          leftIcon={<IconLupa className="h-4 w-4" />}
        />
      </Card>

      {/* Lista desktop */}
      {clientesFiltrados.length > 0 && (
        <Card className="hidden overflow-hidden p-0 lg:block" padding="none">
          <div className="overflow-x-auto">
            <table className="w-full min-w-[850px] text-left">
              <thead className="bg-[var(--bg-secondary)] text-[11px] font-black uppercase tracking-wider text-[var(--text-secondary)]">
                <tr>
                  <th className="whitespace-nowrap px-4 py-3">Cliente</th>
                  <th className="whitespace-nowrap px-4 py-3">Teléfono</th>
                  <th className="whitespace-nowrap px-4 py-3">Correo</th>
                  <th className="whitespace-nowrap px-4 py-3">Ciudad</th>
                  <th className="whitespace-nowrap px-4 py-3">Dirección</th>
                  <th className="whitespace-nowrap px-4 py-3 text-center">Acciones</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[var(--border)]">
                {clientesFiltrados.map((cliente) => (
                  <tr
                    key={cliente.id}
                    className="transition hover:bg-[var(--bg-secondary)]/50"
                  >
                    <td className="px-4 py-3 text-sm font-bold text-[var(--text-primary)]">
                      {cliente.nombre}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3 text-sm text-[var(--text-secondary)]">
                      {cliente.telefono || "-"}
                    </td>
                    <td className="max-w-[180px] truncate px-4 py-3 text-sm text-[var(--text-secondary)]">
                      {cliente.correo || "-"}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3 text-sm text-[var(--text-secondary)]">
                      {cliente.ciudad || "-"}
                    </td>
                    <td className="max-w-[200px] truncate px-4 py-3 text-sm text-[var(--text-secondary)]">
                      {cliente.direccion || "-"}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-center gap-1.5">
                        <Button
                          variant="secondary"
                          size="sm"
                          leftIcon={<IconHistorial className="h-3.5 w-3.5" />}
                          onClick={() => abrirHistorial(cliente)}
                        >
                          Historial
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          leftIcon={<IconEditar className="h-3.5 w-3.5" />}
                          onClick={() => editarCliente(cliente)}
                        >
                          Editar
                        </Button>
                        <Button
                          variant="danger"
                          size="sm"
                          leftIcon={<IconBorrar className="h-3.5 w-3.5" />}
                          disabled={eliminando === cliente.id}
                          onClick={() => eliminarCliente(cliente)}
                        >
                          {eliminando === cliente.id ? "Eliminando..." : "Eliminar"}
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {/* Lista mobile */}
      {clientesFiltrados.length > 0 && (
        <div className="grid gap-3 lg:hidden">
          {clientesFiltrados.map((cliente) => (
            <Card key={cliente.id} padding="sm">
              <div className="mb-2">
                <p className="text-[10px] font-bold uppercase tracking-wider text-[var(--text-muted)]">
                  Cliente
                </p>
                <p className="text-base font-black text-[var(--text-primary)]">{cliente.nombre}</p>
              </div>

              <div className="mb-3 grid gap-1.5 text-sm">
                {cliente.telefono && (
                  <div className="flex items-center gap-1.5 text-xs text-[var(--text-secondary)]">
                    <IconTelefono className="h-3.5 w-3.5 shrink-0" />
                    {cliente.telefono}
                  </div>
                )}
                {cliente.correo && (
                  <div className="flex items-center gap-1.5 text-xs text-[var(--text-secondary)]">
                    <IconCorreo className="h-3.5 w-3.5 shrink-0" />
                    {cliente.correo}
                  </div>
                )}
                {cliente.ciudad && (
                  <div className="flex items-center gap-1.5 text-xs text-[var(--text-secondary)]">
                    <IconUbicacion className="h-3.5 w-3.5 shrink-0" />
                    {cliente.ciudad}
                  </div>
                )}
                {cliente.direccion && (
                  <div className="flex items-start gap-1.5 text-xs text-[var(--text-secondary)]">
                    <IconDireccion className="mt-0.5 h-3.5 w-3.5 shrink-0" />
                    <span className="line-clamp-2">{cliente.direccion}</span>
                  </div>
                )}
              </div>

              <div className="grid grid-cols-3 gap-1.5">
                <Button
                  variant="secondary"
                  size="sm"
                  fullWidth
                  leftIcon={<IconHistorial className="h-3.5 w-3.5" />}
                  onClick={() => abrirHistorial(cliente)}
                >
                  Historial
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  fullWidth
                  leftIcon={<IconEditar className="h-3.5 w-3.5" />}
                  onClick={() => editarCliente(cliente)}
                >
                  Editar
                </Button>
                <Button
                  variant="danger"
                  size="sm"
                  fullWidth
                  leftIcon={<IconBorrar className="h-3.5 w-3.5" />}
                  disabled={eliminando === cliente.id}
                  onClick={() => eliminarCliente(cliente)}
                >
                  {eliminando === cliente.id ? "..." : "Eliminar"}
                </Button>
              </div>
            </Card>
          ))}
        </div>
      )}

      {/* Empty state */}
      {clientesFiltrados.length === 0 && (
        <Card className="p-6 text-center md:p-8">
          <span className="text-4xl">👥</span>
          <h3 className="mt-4 text-base font-black text-[var(--text-primary)]">
            {clientes.length === 0 ? "No hay clientes registrados" : "No se encontraron clientes"}
          </h3>
          <p className="mt-1 text-xs text-[var(--text-muted)]">
            {clientes.length === 0
              ? "Registra tu primer cliente usando el formulario de arriba."
              : "Ajusta la búsqueda para ver resultados."}
          </p>
        </Card>
      )}

      {/* Modal historial */}
      <Modal
        isOpen={!!clienteHistorial}
        onClose={cerrarHistorial}
        title={`Historial de envíos`}
        description={clienteHistorial ? `Cliente: ${clienteHistorial.nombre}` : ""}
        size="lg"
      >
        {cargandoHistorial ? (
          <div className="flex items-center gap-3 py-6">
            <div className="h-8 w-8 animate-spin rounded-full border-[3px] border-[var(--border)] border-t-[var(--accent)]" />
            <p className="text-sm text-[var(--text-secondary)]">Cargando envíos...</p>
          </div>
        ) : guiasHistorial.length === 0 ? (
          <div className="py-6 text-center">
            <span className="text-3xl">📭</span>
            <p className="mt-3 text-sm text-[var(--text-secondary)]">
              Este cliente no tiene guías registradas.
            </p>
          </div>
        ) : (
          <div className="space-y-2">
            {guiasHistorial.map((guia) => {
              const cajasCount = cajasHistorial.filter(
                (c) => String(c.guia_id) === String(guia.id)
              ).length;

              return (
                <div
                  key={String(guia.id)}
                  className="rounded-lg border border-[var(--border)] bg-[var(--bg-primary)] p-3"
                >
                  <div className="mb-2 flex flex-wrap items-start justify-between gap-2">
                    <div className="min-w-0">
                      <p className="text-[10px] font-bold uppercase tracking-wider text-[var(--text-muted)]">
                        Guía
                      </p>
                      <p className="text-sm font-black text-[var(--accent)]">{obtenerNumeroGuia(guia)}</p>
                    </div>
                    <Badge variant={obtenerVarianteEstado(guia.estado)} size="sm">
                      {guia.estado || "Sin estado"}
                    </Badge>
                  </div>

                  <div className="grid grid-cols-2 gap-2 text-xs sm:grid-cols-3">
                    <div>
                      <p className="text-[10px] font-bold uppercase tracking-wider text-[var(--text-muted)]">
                        Fecha
                      </p>
                      <p className="text-[var(--text-secondary)]">
                        {formatearFecha(obtenerFecha(guia))}
                      </p>
                    </div>
                    <div>
                      <p className="text-[10px] font-bold uppercase tracking-wider text-[var(--text-muted)]">
                        Destino
                      </p>
                      <p className="text-[var(--text-secondary)]">{guia.ciudad || "-"}</p>
                    </div>
                    <div>
                      <p className="text-[10px] font-bold uppercase tracking-wider text-[var(--text-muted)]">
                        Cajas
                      </p>
                      <p className="text-[var(--text-secondary)]">{cajasCount}</p>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </Modal>
    </PageLayout>
  );
}

/* =============================================================
   ICONOS
============================================================= */

function IconLupa({ className = "h-5 w-5" }: { className?: string }) {
  return (
    <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
    </svg>
  );
}

function IconEditar({ className = "h-4 w-4" }: { className?: string }) {
  return (
    <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.433-4.433l1.434-1.434a2 2 0 000-2.828l-1.172-1.172a2 2 0 00-2.828 0L15 6.586M17 15l-5.707-5.707" />
    </svg>
  );
}

function IconBorrar({ className = "h-4 w-4" }: { className?: string }) {
  return (
    <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
    </svg>
  );
}

function IconHistorial({ className = "h-4 w-4" }: { className?: string }) {
  return (
    <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
    </svg>
  );
}

function IconTelefono({ className = "h-4 w-4" }: { className?: string }) {
  return (
    <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
    </svg>
  );
}

function IconCorreo({ className = "h-4 w-4" }: { className?: string }) {
  return (
    <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
    </svg>
  );
}

function IconUbicacion({ className = "h-4 w-4" }: { className?: string }) {
  return (
    <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
    </svg>
  );
}

function IconDireccion({ className = "h-4 w-4" }: { className?: string }) {
  return (
    <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
    </svg>
  );
}
