"use client";

import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { ASSISTANT_TOGGLE_EVENT } from "@/components/AssistantDrawer";
import { DEMO_AUTH_EMAIL_COOKIE, DEMO_AUTH_ROLE_COOKIE } from "@/lib/auth/demoAuth";
import { isTeacherEmailAllowed, readTeacherEmailsBrowser } from "@/lib/auth/teacherAllowlist";
import { supabaseBrowser } from "@/lib/supabase/browser";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

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 router = useRouter();
  const [userEmail, setUserEmail] = useState<string | null>(null);
  const [isTeacher, setIsTeacher] = useState(false);

  const teacherEmails = useMemo(() => readTeacherEmailsBrowser(), []);

  useEffect(() => {
    const client = supabaseBrowser();
    if (!client) {
      const cookieMap = new Map(
        document.cookie
          .split(";")
          .map((entry) => entry.trim())
          .filter(Boolean)
          .map((entry) => {
            const [key, ...rest] = entry.split("=");
            return [key, decodeURIComponent(rest.join("="))] as const;
          }),
      );

      const email = cookieMap.get(DEMO_AUTH_EMAIL_COOKIE) ?? null;
      const role = cookieMap.get(DEMO_AUTH_ROLE_COOKIE) ?? "";
      setUserEmail(email);
      setIsTeacher(role === "teacher" || isTeacherEmailAllowed(email, teacherEmails));
      return;
    }

    let mounted = true;

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

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

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

  const links = useMemo(() => {
    if (!isTeacher) return navLinks;
    return [...navLinks, { href: "/teacher", label: "Teacher Dashboard" }];
  }, [isTeacher]);

  const authNode = useMemo(() => {
    if (!userEmail) {
      return (
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" asChild>
            <Link href="/auth/login">Login</Link>
          </Button>
          <Button size="sm" asChild>
            <Link href="/auth/signup">Sign up</Link>
          </Button>
        </div>
      );
    }

    return (
      <div className="flex items-center gap-2 text-sm">
        <span className="hidden max-w-36 truncate text-muted-foreground sm:inline-block">{userEmail}</span>
        {!isTeacher ? (
          <Link
            className="inline-flex items-center rounded-md border border-amber-300 bg-amber-50 px-2 py-1 text-xs font-semibold text-amber-900"
            href="/auth/login?role=teacher"
          >
            Teacher area (Teacher only)
          </Link>
        ) : null}
        <Button
          variant="outline"
          size="sm"
          onClick={async () => {
            const client = supabaseBrowser();
            if (!client) {
              document.cookie = `${DEMO_AUTH_EMAIL_COOKIE}=; path=/; max-age=0`;
              document.cookie = `${DEMO_AUTH_ROLE_COOKIE}=; path=/; max-age=0`;
              setUserEmail(null);
              setIsTeacher(false);
              router.refresh();
              return;
            }
            await client.auth.signOut();
          }}
        >
          Logout
        </Button>
      </div>
    );
  }, [isTeacher, router, userEmail]);

  return (
    <header className="sticky top-0 z-40 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
      <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-accent 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-primary md:text-4xl">ACVE</div>
              <div className="-mt-1 text-xs text-muted-foreground md:text-sm">Centro de Estudios</div>
            </div>
          </Link>
          <nav className="hidden items-center gap-1 text-sm lg:flex">
            {links.map((link) => {
              const isActive = pathname === link.href || pathname?.startsWith(`${link.href}/`);
              return (
                <Button
                  key={link.href}
                  variant={isActive ? "default" : "ghost"}
                  asChild
                  className={cn("rounded-xl text-sm font-semibold", !isActive && "text-muted-foreground hover:text-primary")}
                >
                  <Link href={link.href}>{link.label}</Link>
                </Button>
              );
            })}
          </nav>
        </div>

        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            className="border-primary/20 text-primary hover:bg-primary/5 hover:text-primary"
            onClick={() => window.dispatchEvent(new Event(ASSISTANT_TOGGLE_EVENT))}
          >
            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">
        {links.map((link) => {
          const isActive = pathname === link.href;
          return (
            <Button
              key={link.href}
              variant={isActive ? "default" : "ghost"}
              size="sm"
              asChild
              className="whitespace-nowrap rounded-xl"
            >
              <Link href={link.href}>{link.label}</Link>
            </Button>
          );
        })}
      </nav>
    </header>
  );
}
