"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { FormEvent, useEffect, useState, type ReactNode } from "react";
import { ADMIN_MODULES } from "@/lib/admin-modules";
import { useAdmin } from "@/context/AdminContext";

function StatusPill({ status }: { status: "activo" | "en_desarrollo" }) {
  if (status === "activo") {
    return (
      <span className="text-[10px] tracking-[0.14em] uppercase border border-ot-green text-ot-green px-2 py-0.5">
        Activo
      </span>
    );
  }
  return (
    <span className="text-[10px] tracking-[0.14em] uppercase border border-ot-gold text-ot-gold px-2 py-0.5">
      En desarrollo
    </span>
  );
}

function LoginForm() {
  const { refresh } = useAdmin();
  const [email, setEmail] = useState("admin@ot.azulado.cloud");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setBusy(true);
    setError("");
    const res = await fetch("/api/ops/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password }),
    });
    setBusy(false);
    if (!res.ok) {
      const data = (await res.json().catch(() => ({}))) as { message?: string };
      setError(data.message || "No se pudo iniciar sesión.");
      return;
    }
    await refresh();
  };

  return (
    <div className="min-h-screen bg-ot-cream flex items-center justify-center px-4">
      <form
        onSubmit={onSubmit}
        className="w-full max-w-md bg-white p-8 border border-black/10"
      >
        <p className="ot-eyebrow">OLD TENNIS</p>
        <h1 className="font-serif text-4xl mt-2">Panel de negocio</h1>
        <p className="text-sm text-ot-muted mt-2 mb-6">
          Acceso exclusivo para administrar pedidos, inventario, ventas y más.
        </p>
        <label className="block text-xs tracking-[0.14em] uppercase text-ot-muted mb-1">
          Correo admin
        </label>
        <input
          type="email"
          className="w-full border border-black/15 px-4 py-3 text-sm outline-none focus:border-ot-green mb-3"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
        <label className="block text-xs tracking-[0.14em] uppercase text-ot-muted mb-1">
          Clave
        </label>
        <input
          type="password"
          className="w-full border border-black/15 px-4 py-3 text-sm outline-none focus:border-ot-green"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
        />
        <button className="ot-btn w-full mt-5" type="submit" disabled={busy}>
          {busy ? "Entrando…" : "Entrar al negocio"}
        </button>
        {error ? <p className="text-sm text-red-700 mt-3">{error}</p> : null}
      </form>
    </div>
  );
}

export function NegocioShell({ children }: { children: ReactNode }) {
  const { loading, authenticated, email, logout } = useAdmin();
  const pathname = usePathname();
  const router = useRouter();

  useEffect(() => {
    if (!loading && !authenticated && pathname !== "/negocio") {
      router.replace("/negocio");
    }
  }, [loading, authenticated, pathname, router]);

  if (loading) {
    return (
      <div className="min-h-screen bg-ot-cream flex items-center justify-center text-ot-muted">
        Cargando panel…
      </div>
    );
  }

  if (!authenticated) {
    return <LoginForm />;
  }

  return (
    <div className="min-h-screen bg-ot-cream">
      <header className="bg-ot-green text-ot-cream px-4 sm:px-6 py-4 flex flex-wrap items-center justify-between gap-3">
        <div>
          <p className="text-[11px] tracking-[0.22em] uppercase text-ot-gold">
            OLD TENNIS · Negocio
          </p>
          <p className="font-serif text-2xl mt-0.5">Panel de administración</p>
        </div>
        <div className="flex items-center gap-3 text-sm">
          <span className="text-ot-cream/80">{email}</span>
          <Link href="/" className="underline underline-offset-4 text-ot-cream/90">
            Ver tienda
          </Link>
          <button
            type="button"
            className="border border-ot-cream/40 px-3 py-1.5 text-[11px] tracking-[0.14em] uppercase"
            onClick={async () => {
              await logout();
              router.push("/negocio");
            }}
          >
            Cerrar sesión
          </button>
        </div>
      </header>

      <div className="ot-container py-8 grid lg:grid-cols-[240px_1fr] gap-8">
        <aside className="space-y-1 h-fit lg:sticky lg:top-6">
          <Link
            href="/negocio"
            className={`block px-3 py-2.5 text-sm ${
              pathname === "/negocio"
                ? "bg-ot-green text-ot-cream"
                : "hover:bg-black/5"
            }`}
          >
            Resumen
          </Link>
          {ADMIN_MODULES.map((mod) => (
            <Link
              key={mod.id}
              href={mod.href}
              className={`block px-3 py-2.5 text-sm ${
                pathname.startsWith(mod.href)
                  ? "bg-ot-green text-ot-cream"
                  : "hover:bg-black/5"
              }`}
            >
              <span className="flex items-center justify-between gap-2">
                <span>
                  <span className="text-[10px] tracking-[0.12em] uppercase opacity-70 mr-1">
                    {mod.phase}.
                  </span>
                  {mod.title}
                </span>
              </span>
            </Link>
          ))}
        </aside>
        <div>{children}</div>
      </div>
    </div>
  );
}

export { StatusPill };
