import { useEffect, useState } from "react";
import { SignedIn, SignedOut } from "@clerk/clerk-react";
import { ArchiveIcon, BellIcon, BookOpenIcon, EarthIcon, LibraryIcon, PaperclipIcon, SettingsIcon, User2Icon, UsersIcon } from "lucide-react";
import { NavLink } from "react-router-dom";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useNotifications } from "@/hooks/useUserQueries";
import { cn } from "@/lib/utils";
import { Routes } from "@/router";
import { UserNotification_Status } from "@/types/proto/api/v1/user_service_pb";
import { useTranslate } from "@/utils/i18n";
import MemosLogo from "./MemosLogo";
import UserMenu from "./UserMenu";

interface NavLinkItem {
  id: string;
  path: string;
  title: string;
  icon: React.ReactNode;
  requiresAuth?: boolean;
}

interface Props {
  collapsed?: boolean;
  className?: string;
}

const Navigation = (props: Props) => {
  const { collapsed, className } = props;
  const t = useTranslate();
  const { data: notifications = [] } = useNotifications();

  const unreadCount = notifications.filter((n) => n.status === UserNotification_Status.UNREAD).length;

  const mainNavLinks: NavLinkItem[] = [
    {
      id: "header-memos",
      path: Routes.ROOT,
      title: t("common.memos"),
      icon: <LibraryIcon className="w-5 h-5 shrink-0" />,
    },
    {
      id: "header-explore",
      path: Routes.EXPLORE,
      title: t("common.explore"),
      icon: <EarthIcon className="w-5 h-5 shrink-0" />,
    },
    {
      id: "header-attachments",
      path: Routes.ATTACHMENTS,
      title: t("common.attachments"),
      icon: <PaperclipIcon className="w-5 h-5 shrink-0" />,
      requiresAuth: true,
    },
    {
      id: "header-inbox",
      path: Routes.INBOX,
      title: t("common.inbox"),
      icon: (
        <div className="relative">
          <BellIcon className="w-5 h-5 shrink-0" />
          {unreadCount > 0 && (
            <span className="absolute -top-1.5 -right-1.5 min-w-[16px] h-[16px] px-0.5 flex items-center justify-center bg-amber-500 text-white text-[9px] font-bold rounded-full border-2 border-background animate-pulse">
              {unreadCount > 99 ? "99+" : unreadCount}
            </span>
          )}
        </div>
      ),
      requiresAuth: true,
    },
    {
      id: "header-archived",
      path: Routes.ARCHIVED,
      title: t("common.archived"),
      icon: <ArchiveIcon className="w-5 h-5 shrink-0" />,
      requiresAuth: true,
    },
  ];

  // Dynamic teams from API
  const [teams, setTeams] = useState<{ id: string; name: string }[]>([]);

  useEffect(() => {
    const fetchTeams = async () => {
      try {
        const { listTeams } = await import("@/service/teamService");
        const data = await listTeams();
        setTeams(data.map((t) => ({ id: t.id, name: t.name })));
      } catch {
        // Not logged in or API error — ignore
      }
    };
    fetchTeams();
  }, []);

  const teamNavLinks: NavLinkItem[] = [
    // "Teams" overview link
    {
      id: "header-teams",
      path: Routes.TEAMS,
      title: "Teams",
      icon: <UsersIcon className="w-5 h-5 shrink-0" />,
      requiresAuth: true,
    },
    // Individual team links
    ...teams.map((team) => ({
      id: `header-team-${team.id}`,
      path: `/app/teams/${team.id}`,
      title: team.name,
      icon: (
        <div className="w-5 h-5 rounded-md bg-amber-500/20 text-amber-600 dark:text-amber-400 flex items-center justify-center text-[11px] font-bold shrink-0">
          {team.name.charAt(0).toUpperCase()}
        </div>
      ),
      requiresAuth: true,
    })),
  ];

  const systemNavLinks: NavLinkItem[] = [
    {
      id: "header-setting",
      path: Routes.SETTING,
      title: t("common.settings"),
      icon: <SettingsIcon className="w-5 h-5 shrink-0" />,
      requiresAuth: true,
    },
    {
      id: "header-about",
      path: Routes.ABOUT,
      title: t("common.about"),
      icon: <BookOpenIcon className="w-5 h-5 shrink-0" />,
    },
  ];

  const renderNavLink = (navLink: NavLinkItem) => (
    <NavLink
      className={({ isActive }) =>
        cn(
          "relative px-2 py-2 rounded-xl flex flex-row items-center text-sm text-sidebar-foreground transition-all duration-200 active:scale-[0.98]",
          collapsed ? "" : "w-full px-3",
          isActive
            ? "bg-sidebar-accent text-sidebar-accent-foreground font-semibold"
            : "opacity-70 hover:opacity-100 hover:bg-sidebar-accent/50 hover:text-sidebar-accent-foreground",
        )
      }
      key={navLink.id}
      to={navLink.path}
      id={navLink.id}
      viewTransition
    >
      {({ isActive }) => (
        <>
          {/* Active accent bar */}
          {isActive && (
            <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-4 rounded-full bg-amber-500" />
          )}
          {props.collapsed ? (
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <div>{navLink.icon}</div>
                </TooltipTrigger>
                <TooltipContent side="right">
                  <p>{navLink.title}</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          ) : (
            navLink.icon
          )}
          {!props.collapsed && <span className="ml-3 truncate">{navLink.title}</span>}
        </>
      )}
    </NavLink>
  );

  const sectionLabel = (label: string) =>
    !collapsed ? (
      <div className="px-3 pt-3 pb-1">
        <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground/40 select-none">
          {label}
        </span>
      </div>
    ) : (
      <div className="mx-auto my-1 w-4 border-t border-border/30" />
    );

  return (
    <header className={cn("w-full h-full overflow-auto flex flex-col justify-between items-start gap-4 hide-scrollbar", className)}>
      <div
        className="w-full px-1 py-1 flex flex-col justify-start items-start space-y-1 overflow-auto overflow-x-hidden hide-scrollbar shrink"
        style={{
          maskImage: "linear-gradient(to bottom, black 85%, transparent 100%)",
          WebkitMaskImage: "linear-gradient(to bottom, black 85%, transparent 100%)",
        }}
      >
        <SignedIn>
          <NavLink className="mb-3 cursor-default" to={Routes.ROOT}>
            <MemosLogo collapsed={collapsed} />
          </NavLink>
        </SignedIn>
        <SignedOut>
          <NavLink className="mb-3 cursor-default" to={Routes.EXPLORE}>
            <MemosLogo collapsed={collapsed} />
          </NavLink>
        </SignedOut>

        {/* Main section */}
        {mainNavLinks.map(renderNavLink)}

        {/* Teams section */}
        <SignedIn>
          {sectionLabel("Teams")}
          {teamNavLinks.map(renderNavLink)}
        </SignedIn>

        {/* System section */}
        {sectionLabel("System")}
        {systemNavLinks.map(renderNavLink)}
      </div>

      <div className={cn("w-full flex flex-col justify-end", props.collapsed ? "items-center" : "items-start pl-3")}>
        <SignedIn>
          <UserMenu collapsed={collapsed} />
        </SignedIn>
        <SignedOut>
          <NavLink
            to={Routes.AUTH}
            className={cn(
              "relative px-2 py-2 rounded-xl flex flex-row items-center text-sm text-sidebar-foreground transition-all duration-200 active:scale-[0.98] opacity-70 hover:opacity-100 hover:bg-sidebar-accent/50",
              collapsed ? "" : "w-full px-3",
            )}
          >
            {collapsed ? (
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <div>
                      <User2Icon className="w-5 h-5 shrink-0" />
                    </div>
                  </TooltipTrigger>
                  <TooltipContent side="right">
                    <p>{t("common.sign-in")}</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            ) : (
              <>
                <User2Icon className="w-5 h-5 shrink-0" />
                <span className="ml-3 truncate">{t("common.sign-in")}</span>
              </>
            )}
          </NavLink>
        </SignedOut>
      </div>
    </header>
  );
};

export default Navigation;
