"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import type { LucideIcon } from "lucide-react";
import {
  ShieldCheck, Menu, X, Crown, GitCompare, LayoutDashboard,
  ScanText, Settings, LogIn, Zap, Sparkles, CreditCard, UserCircle,
  LogOut, Users
} from "lucide-react";
import { useState, useEffect } from "react";
import { createClient } from "@/lib/supabase/client";

interface NavLink {
  href: string;
  label: string;
  icon?: LucideIcon;
}

export function Nav() {
  const [open, setOpen] = useState(false);
  const [userEmail, setUserEmail] = useState<string | null>(null);
  const [userRole, setUserRole] = useState<string | null>(null);
  const [userTeam, setUserTeam] = useState<string | null>(null);
  const [loaded, setLoaded] = useState(false);
  const pathname = usePathname();
  const isLoggedIn = !!userEmail;
  const isAdmin = userRole === "admin";
  const hasTeam = !!userTeam;

  useEffect(() => {
    try {
      const supabase = createClient();
      supabase.auth.getUser().then(async ({ data, error }) => {
        if (error) {
          console.error("Auth error:", error);
          setLoaded(true);
          return;
        }
        const user = data.user;
        setUserEmail(user?.email || null);
        if (user) {
          try {
            const { data: profile } = await supabase
              .from("profiles")
              .select("role, team_id")
              .eq("id", user.id)
              .single();
            setUserRole(profile?.role || "user");
            setUserTeam(profile?.team_id || null);
          } catch (err) {
            console.error("Profile error:", err);
          }
        }
        setLoaded(true);
      }).catch(err => {
        console.error("Unexpected error:", err);
        setLoaded(true);
      });
    } catch (err) {
      console.error("Supabase client init error:", err);
      // Fallback for when env variables are not found/configured
      setLoaded(true);
    }
  }, []);

  async function handleSignOut() {
    const supabase = createClient();
    await supabase.auth.signOut();
    setUserEmail(null);
    setUserRole(null);
    setUserTeam(null);
    window.location.href = "/";
  }

  // Public links - always visible
  const mainLinks: NavLink[] = [
    { href: "/#features", label: "Features", icon: Sparkles },
    { href: "/#pricing", label: "Pricing", icon: CreditCard },
    { href: "/dashboard-pages/analyze", label: "Scanner", icon: ScanText },
    { href: "/dashboard-pages/compare", label: "Compare", icon: GitCompare },
  ];

  return (
    <nav className="sticky top-0 z-50 bg-white/80 backdrop-blur-md border-b border-zinc-100">
      <div className="max-w-6xl mx-auto px-4 sm:px-5 h-14 flex items-center justify-between">
        {/* Logo */}
        <Link href="/" className="flex items-center gap-2">
          <ShieldCheck className="w-5 h-5 text-zinc-900" strokeWidth={2.2} />
          <span className="font-semibold text-[15px] tracking-tight text-zinc-900">ClauseGuard</span>
          <span className="hidden sm:inline text-[10px] font-medium text-zinc-400 ml-1 border border-zinc-200 px-1.5 py-0.5 rounded">v4.0</span>
        </Link>

        {/* Desktop Nav */}
        <div className="hidden md:flex items-center gap-0.5">
          {/* Public links - always visible */}
          {mainLinks.map((l) => {
            const isActive = pathname === l.href;
            return (
              <Link key={l.href} href={l.href}
                className={`flex items-center gap-1.5 px-2.5 py-1.5 text-[13px] rounded-md transition-colors ${
                  isActive ? "text-zinc-900 bg-zinc-100 font-medium" : "text-zinc-500 hover:text-zinc-900 hover:bg-zinc-50"
                }`}>
                {l.label}
              </Link>
            );
          })}

          {/* Loading skeleton while auth state resolves */}
          {!loaded && (
            <>
              <div className="w-px h-4 bg-zinc-200 mx-1.5" />
              <div className="flex items-center gap-2">
                <div className="w-14 h-7 bg-zinc-100 rounded-md animate-pulse" />
                <div className="w-20 h-7 bg-zinc-900/10 rounded-md animate-pulse" />
              </div>
            </>
          )}

          {/* Logged-in links */}
          {loaded && isLoggedIn && (
            <>
              {/* Dashboard */}
              <Link href="/dashboard-pages/dashboard"
                className={`flex items-center gap-1.5 px-2.5 py-1.5 text-[13px] rounded-md transition-colors ${
                  pathname === "/dashboard-pages/dashboard"
                    ? "text-zinc-900 bg-zinc-100 font-medium"
                    : "text-zinc-500 hover:text-zinc-900 hover:bg-zinc-50"
                }`}>
                <LayoutDashboard className="w-3.5 h-3.5" />
                Dashboard
              </Link>

              {/* Team - only when user belongs to a team */}
              {hasTeam && (
                <Link href="/dashboard-pages/team"
                  className={`flex items-center gap-1.5 px-2.5 py-1.5 text-[13px] rounded-md transition-colors ${
                    pathname === "/dashboard-pages/team"
                      ? "text-zinc-900 bg-zinc-100 font-medium"
                      : "text-zinc-500 hover:text-zinc-900 hover:bg-zinc-50"
                  }`}>
                  <Users className="w-3.5 h-3.5" />
                  Team
                </Link>
              )}

              {/* Admin - only for admin role */}
              {isAdmin && (
                <Link href="/admin"
                  className={`flex items-center gap-1.5 px-2.5 py-1.5 text-[13px] rounded-md transition-colors ${
                    pathname === "/admin"
                      ? "text-amber-700 bg-amber-50 font-medium"
                      : "text-amber-600 hover:text-amber-700 hover:bg-amber-50"
                  }`}>
                  <Crown className="w-3.5 h-3.5" />
                  Admin
                </Link>
              )}

              <div className="w-px h-4 bg-zinc-200 mx-1.5" />

              {/* Settings */}
              <Link href="/dashboard-pages/settings"
                className={`flex items-center gap-1.5 px-2.5 py-1.5 text-[13px] rounded-md transition-colors ${
                  pathname?.includes("settings")
                    ? "text-zinc-900 bg-zinc-100 font-medium"
                    : "text-zinc-500 hover:text-zinc-900 hover:bg-zinc-50"
                }`}>
                <Settings className="w-3.5 h-3.5" />
                Settings
              </Link>
              {/* User indicator with hover dropdown */}
              <div className="relative group ml-1">
                <button className="flex items-center gap-1.5 px-2.5 py-1.5 text-[13px] text-zinc-500 hover:text-zinc-900 rounded-md hover:bg-zinc-50 transition-colors">
                  <UserCircle className="w-3.5 h-3.5" />
                  <span className="max-w-[100px] truncate">{userEmail?.split("@")[0]}</span>
                </button>
                {/* Dropdown on hover */}
                <div className="absolute right-0 top-full mt-1 w-52 bg-white border border-zinc-200 rounded-xl shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-150 z-50">
                  <div className="px-3 py-2.5 border-b border-zinc-100">
                    <p className="text-xs text-zinc-400">Signed in as</p>
                    <p className="text-sm text-zinc-700 font-medium truncate">{userEmail}</p>
                    {isAdmin && (
                      <span className="inline-flex items-center gap-1 mt-1 text-[10px] bg-amber-50 text-amber-700 border border-amber-200 px-1.5 py-0.5 rounded">
                        <Crown className="w-2.5 h-2.5" /> Admin
                      </span>
                    )}
                  </div>
                  <div className="py-1">
                    <Link href="/dashboard-pages/settings"
                      className="flex items-center gap-2 px-3 py-2 text-sm text-zinc-600 hover:bg-zinc-50">
                      <Settings className="w-3.5 h-3.5 text-zinc-400" /> Settings
                    </Link>
                    {isAdmin && (
                      <Link href="/admin"
                        className="flex items-center gap-2 px-3 py-2 text-sm text-amber-600 hover:bg-amber-50">
                        <Crown className="w-3.5 h-3.5" /> Admin Panel
                      </Link>
                    )}
                  </div>
                  <div className="border-t border-zinc-100 py-1">
                    <button onClick={handleSignOut}
                      className="flex items-center gap-2 px-3 py-2 text-sm text-red-600 hover:bg-red-50 w-full text-left">
                      <LogOut className="w-3.5 h-3.5" /> Sign out
                    </button>
                  </div>
                </div>
              </div>

              {/* New scan CTA */}
              <Link href="/dashboard-pages/analyze"
                className="ml-1 px-3 py-1.5 text-[13px] font-medium text-white bg-zinc-900 rounded-md hover:bg-zinc-800 transition-colors flex items-center gap-1.5">
                <Zap className="w-3.5 h-3.5" /> New scan
              </Link>
            </>
          )}

          {/* Logged-out links */}
          {loaded && !isLoggedIn && (
            <>
              <div className="w-px h-4 bg-zinc-200 mx-1.5" />

              <Link href="/auth/login"
                className={`flex items-center gap-1.5 px-2.5 py-1.5 text-[13px] rounded-md transition-colors ${
                  pathname === "/auth/login"
                    ? "text-zinc-900 bg-zinc-100 font-medium"
                    : "text-zinc-500 hover:text-zinc-900 hover:bg-zinc-50"
                }`}>
                <LogIn className="w-3.5 h-3.5" /> Log in
              </Link>

              <Link href="/auth/signup"
                className="ml-1 px-3 py-1.5 text-[13px] font-medium text-white bg-zinc-900 rounded-md hover:bg-zinc-800 transition-colors">
                Sign up
              </Link>
            </>
          )}
        </div>

        {/* Mobile hamburger */}
        <button className="md:hidden p-1.5 rounded-md hover:bg-zinc-100" onClick={() => setOpen(!open)}>
          {open ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
        </button>
      </div>

      {/* Mobile Menu */}
      {open && (
        <div className="md:hidden border-t border-zinc-100 bg-white px-5 py-3 space-y-0.5">
          {/* Public links */}
          {mainLinks.map((l) => {
            const Icon = l.icon ?? null;
            const isActive = pathname === l.href;
            return (
              <Link key={l.href} href={l.href} onClick={() => setOpen(false)}
                className={`flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-md ${
                  isActive ? "text-zinc-900 bg-zinc-100 font-medium" : "text-zinc-600 hover:bg-zinc-50"
                }`}>
                {Icon && <Icon className="w-4 h-4 text-zinc-400" />}
                {l.label}
              </Link>
            );
          })}

          {/* Mobile loading skeleton */}
          {!loaded && (
            <>
              <div className="h-px bg-zinc-100 my-1.5" />
              <div className="flex flex-col gap-2 px-3">
                <div className="w-full h-10 bg-zinc-100 rounded-lg animate-pulse" />
                <div className="w-full h-10 bg-zinc-900/10 rounded-lg animate-pulse" />
              </div>
            </>
          )}

          {/* Mobile: Logged-in links */}
          {loaded && isLoggedIn && (
            <>
              <div className="h-px bg-zinc-100 my-1.5" />

              {/* User info banner */}
              <div className="px-3 py-2">
                <p className="text-xs text-zinc-400">Signed in as</p>
                <p className="text-sm text-zinc-700 font-medium truncate">{userEmail}</p>
              </div>

              <Link href="/dashboard-pages/dashboard" onClick={() => setOpen(false)}
                className={`flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-md ${
                  pathname === "/dashboard-pages/dashboard"
                    ? "text-zinc-900 bg-zinc-100 font-medium"
                    : "text-zinc-600 hover:bg-zinc-50"
                }`}>
                <LayoutDashboard className="w-4 h-4 text-zinc-400" /> Dashboard
              </Link>

              <Link href="/dashboard-pages/settings" onClick={() => setOpen(false)}
                className={`flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-md ${
                  pathname?.includes("settings")
                    ? "text-zinc-900 bg-zinc-100 font-medium"
                    : "text-zinc-600 hover:bg-zinc-50"
                }`}>
                <Settings className="w-4 h-4 text-zinc-400" /> Settings
              </Link>

              {/* Team link */}
              {hasTeam && (
                <Link href="/dashboard-pages/team" onClick={() => setOpen(false)}
                  className={`flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-md ${
                    pathname === "/dashboard-pages/team"
                      ? "text-zinc-900 bg-zinc-100 font-medium"
                      : "text-zinc-600 hover:bg-zinc-50"
                  }`}>
                  <Users className="w-4 h-4 text-zinc-400" /> Team
                </Link>
              )}

              {/* Admin link */}
              {isAdmin && (
                <Link href="/admin" onClick={() => setOpen(false)}
                  className={`flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-md ${
                    pathname === "/admin"
                      ? "text-amber-700 bg-amber-50 font-medium"
                      : "text-amber-600 hover:bg-amber-50"
                  }`}>
                  <Crown className="w-4 h-4" /> Admin Panel
                </Link>
              )}

              <div className="h-px bg-zinc-100 my-1.5" />

              {/* New Scan CTA */}
              <Link href="/dashboard-pages/analyze" onClick={() => setOpen(false)}
                className="flex items-center justify-center gap-2 px-3 py-2.5 text-sm font-medium text-white bg-zinc-900 rounded-lg hover:bg-zinc-800">
                <Zap className="w-4 h-4" /> New Scan
              </Link>

              {/* Sign out */}
              <button onClick={() => { handleSignOut(); setOpen(false); }}
                className="flex items-center gap-2.5 px-3 py-2.5 text-sm text-red-600 rounded-md hover:bg-red-50 w-full">
                <LogOut className="w-4 h-4" /> Sign out
              </button>
            </>
          )}

          {/* Mobile: Logged-out links */}
          {loaded && !isLoggedIn && (
            <>
              <div className="h-px bg-zinc-100 my-1.5" />

              <Link href="/auth/login" onClick={() => setOpen(false)}
                className={`flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-md ${
                  pathname === "/auth/login"
                    ? "text-zinc-900 bg-zinc-100 font-medium"
                    : "text-zinc-600 hover:bg-zinc-50"
                }`}>
                <LogIn className="w-4 h-4 text-zinc-400" /> Log in
              </Link>

              <Link href="/auth/signup" onClick={() => setOpen(false)}
                className="flex items-center justify-center gap-2 px-3 py-2.5 text-sm font-medium text-white bg-zinc-900 rounded-lg hover:bg-zinc-800">
                Sign up
              </Link>
            </>
          )}
        </div>
      )}
    </nav>
  );
}
