"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { ASSISTANT_TOGGLE_EVENT } from "@/components/AssistantDrawer";
import { supabaseBrowser } from "@/lib/supabase/browser";

type NavLink = {
  href: string;
  label: string;
};

const navLinks: NavLink[] = [
  { href: "/", label: "Home" },
  { href: "/courses", label: "Courses" },
  { href: "/case-studies", label: "Case Studies" },
  { href: "/practice", label: "Practice" },
];

export default function Navbar() {
  const pathname = usePathname();
  const [userEmail, setUserEmail] = useState<string | null>(null);

  const linkClass = (href: string) =>
    pathname === href || pathname?.startsWith(`${href}/`)
      ? "rounded-xl bg-brand px-5 py-3 text-sm font-semibold text-white shadow-sm"
      : "rounded-xl px-5 py-3 text-sm font-semibold text-slate-700 transition-colors hover:text-brand";

  useEffect(() => {
    const client = supabaseBrowser();
    if (!client) return;

    let mounted = true;

    client.auth.getUser().then(({ data }) => {
      if (!mounted) return;
      setUserEmail(data.user?.email ?? null);
    });

    const { data } = client.auth.onAuthStateChange((_event, session) => {
      setUserEmail(session?.user?.email ?? null);
    });

    return () => {
      mounted = false;
      data.subscription.unsubscribe();
    };
  }, []);

  const authNode = useMemo(() => {
    if (!userEmail) {
      return (
        <div className="flex items-center gap-2 text-sm">
          <Link className="rounded-lg border border-slate-300 px-3 py-1.5 hover:bg-slate-50" href="/auth/login">
            Login
          </Link>
          <Link className="rounded-lg bg-brand px-3 py-1.5 text-white hover:brightness-105" href="/auth/signup">
            Sign up
          </Link>
        </div>
      );
    }

    return (
      <div className="flex items-center gap-2 text-sm">
        <span className="max-w-36 truncate text-slate-700">{userEmail}</span>
        <button
          className="rounded-lg border border-slate-300 px-3 py-1.5 hover:bg-slate-50"
          onClick={async () => {
            const client = supabaseBrowser();
            if (!client) return;
            await client.auth.signOut();
          }}
          type="button"
        >
          Logout
        </button>
      </div>
    );
  }, [userEmail]);

  return (
    <header className="sticky top-0 z-40 border-b border-slate-300 bg-[#f7f7f8]/95 backdrop-blur">
      <div className="mx-auto flex w-full max-w-[1300px] items-center justify-between gap-4 px-4 py-3">
        <div className="flex items-center gap-8">
          <Link className="flex items-center gap-3" href="/">
            <div className="rounded-xl bg-[#edd7bc] p-1.5 shadow-sm">
              <Image alt="ACVE logo" className="h-10 w-10 rounded-lg object-cover" height={40} src="/images/logo.png" width={40} />
            </div>
            <div>
              <div className="text-2xl font-bold leading-none tracking-tight text-brand md:text-4xl">ACVE</div>
              <div className="-mt-1 text-xs text-slate-500 md:text-sm">Centro de Estudios</div>
            </div>
          </Link>
          <nav className="hidden items-center gap-1 text-sm lg:flex">
            {navLinks.map((link) => (
              <Link key={link.href} className={linkClass(link.href)} href={link.href}>
                {link.label}
              </Link>
            ))}
          </nav>
        </div>

        <div className="flex items-center gap-2">
          <button
            className="rounded-xl border border-accent bg-white px-4 py-2.5 text-sm font-semibold text-accent hover:bg-amber-50"
            onClick={() => window.dispatchEvent(new Event(ASSISTANT_TOGGLE_EVENT))}
            type="button"
          >
            AI Assistant
          </button>
          {authNode}
        </div>
      </div>
      <nav className="mx-auto flex w-full max-w-[1300px] gap-2 overflow-x-auto px-4 pb-3 text-sm lg:hidden">
        {navLinks.map((link) => (
          <Link key={link.href} className={linkClass(link.href)} href={link.href}>
            {link.label}
          </Link>
        ))}
      </nav>
    </header>
  );
}
