import { useEffect, useState } from "react";
// Removed clerk
import { ArchiveIcon, BellIcon, BookOpenIcon, EarthIcon, FileTextIcon, LibraryIcon, LayersIcon, PaperclipIcon, SettingsIcon, User2Icon, UsersIcon } from "lucide-react";
import { NavLink } from "react-router-dom";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useNotifications, useInboxUnreadCount } 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";
import { useAuth } from "@/contexts/AuthContext";
import { useWorkspace } from "@/contexts/WorkspaceContext";

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 { currentUser } = useAuth();
  const { data: notifications = [] } = useNotifications();
  const { data: unreadMemosCount = 0 } = useInboxUnreadCount();

  const notificationUnreadCount = notifications.filter((n) => n.status === UserNotification_Status.UNREAD).length;
  const totalInboxCount = notificationUnreadCount + unreadMemosCount;

  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-deadlines",
      path: Routes.DEADLINES,
      title: "Deadlines",
      icon: <LayersIcon className="w-5 h-5 shrink-0" />,
      requiresAuth: true,
    },
    {
      id: "header-documents",
      path: Routes.DOCUMENTS,
      title: t("documents.title"),
      icon: <FileTextIcon className="w-5 h-5 shrink-0" />,
      requiresAuth: true,
    },
    {
      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" />
          {(totalInboxCount > 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">
              {totalInboxCount > 99 ? "99+" : totalInboxCount}
            </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%)",
        }}
      >
        {currentUser ? (
          <NavLink className="mb-3 cursor-default" to={Routes.ROOT}>
            <MemosLogo collapsed={collapsed} />
          </NavLink>
        ) : (
          <NavLink className="mb-3 cursor-default" to={Routes.EXPLORE}>
            <MemosLogo collapsed={collapsed} />
          </NavLink>
        )}

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

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

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

      <div className={cn("w-full flex flex-col justify-end gap-2", props.collapsed ? "items-center" : "items-start pl-3")}>
        {/* Workspace Switcher */}
        {currentUser && (
          <WorkspaceSwitcher collapsed={props.collapsed} />
        )}

        {currentUser ? (
          <UserMenu collapsed={props.collapsed} />
        ) : (
          <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>
        )}
      </div>
    </header>
  );
};

// Workspace Switcher Component
interface WorkspaceSwitcherProps {
  collapsed?: boolean;
}

const WorkspaceSwitcher = ({ collapsed }: WorkspaceSwitcherProps) => {
  const { workspaceId, setWorkspaceId } = useWorkspace();
  const t = useTranslate();

  const workspaces = [
    { id: "PERSONAL", label: t("workspace.personal"), icon: "👤" },
    { id: "AI_SALES_CRM", label: t("workspace.aiSales"), icon: "🤖" },
  ] as const;

  const currentWorkspace = workspaces.find((w) => w.id === workspaceId);

  if (collapsed) {
    return (
      <TooltipProvider>
        <Tooltip>
          <TooltipTrigger asChild>
            <button
              onClick={() => {
                // Cycle through workspaces
                const nextIndex = workspaceId === "PERSONAL" ? 1 : 0;
                setWorkspaceId(workspaces[nextIndex].id);
              }}
              className="relative px-2 py-2 rounded-xl flex items-center text-sm text-sidebar-foreground opacity-70 hover:opacity-100 hover:bg-sidebar-accent/50 transition-all"
            >
              <LayersIcon className="w-5 h-5 shrink-0" />
            </button>
          </TooltipTrigger>
          <TooltipContent side="right">
            <p>{t("workspace.switch")}: {currentWorkspace?.label}</p>
          </TooltipContent>
        </Tooltip>
      </TooltipProvider>
    );
  }

  return (
    <div className="w-full px-2 py-1">
      <div className="flex items-center gap-2 px-2 py-2 rounded-xl bg-sidebar-accent/30 border border-border">
        <LayersIcon className="w-4 h-4 shrink-0 text-muted-foreground" />
        <span className="text-xs font-medium text-muted-foreground truncate">{t("workspace.switch")}:</span>
      </div>
      <div className="mt-1 flex flex-col gap-1">
        {workspaces.map((ws) => (
          <button
            key={ws.id}
            onClick={() => setWorkspaceId(ws.id)}
            className={cn(
              "flex items-center gap-2 px-2 py-1.5 rounded-lg text-sm transition-all",
              workspaceId === ws.id
                ? "bg-sidebar-accent text-sidebar-accent-foreground font-medium"
                : "opacity-60 hover:opacity-100 hover:bg-sidebar-accent/50"
            )}
          >
            <span>{ws.icon}</span>
            <span className="truncate">{ws.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
};

export default Navigation;
