import { Home, Inbox, Settings, HelpCircle, Globe } from "lucide-react";
import { Link, useRouterState } from "@tanstack/react-router";
import { useSidebar } from "@/components/ui/sidebar"; // import useSidebar hook
import { useEffect, useState, useRef } from "react";
import { useAtom } from "jotai";
import { dropdownOpenAtom } from "@/atoms/uiAtoms";

import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarRail,
  SidebarTrigger,
} from "@/components/ui/sidebar";
import { ChatList } from "./ChatList";
import { AppList } from "./AppList";
import { ConnectorList } from "./ConnectorList";
import { HelpDialog } from "./HelpDialog"; // Import the new dialog
import { SettingsList } from "./SettingsList";
import { useTranslation } from "react-i18next";

// Menu items.
const items = [
  {
    key: "apps",
    to: "/",
    icon: Home,
  },
  {
    key: "connectors",
    to: "/connectors",
    icon: Globe,
  },
  {
    key: "chat",
    to: "/chat",
    icon: Inbox,
  },
  {
    key: "settings",
    to: "/settings",
    icon: Settings,
  },
];

// Hover state types
type HoverState =
  | "start-hover:app"
  | "start-hover:connector"
  | "start-hover:chat"
  | "start-hover:settings"
  | "clear-hover"
  | "no-hover";

export function AppSidebar() {
  const { t } = useTranslation(["home", "chat", "settings"]);
  const { state, toggleSidebar } = useSidebar(); // retrieve current sidebar state
  const [hoverState, setHoverState] = useState<HoverState>("no-hover");
  const expandedByHover = useRef(false);
  const [isHelpDialogOpen, setIsHelpDialogOpen] = useState(false); // State for dialog
  const [isDropdownOpen] = useAtom(dropdownOpenAtom);

  useEffect(() => {
    if (hoverState.startsWith("start-hover") && state === "collapsed") {
      expandedByHover.current = true;
      toggleSidebar();
    }
    if (
      hoverState === "clear-hover" &&
      state === "expanded" &&
      expandedByHover.current &&
      !isDropdownOpen
    ) {
      toggleSidebar();
      expandedByHover.current = false;
      setHoverState("no-hover");
    }
  }, [hoverState, toggleSidebar, state, setHoverState, isDropdownOpen]);

  const routerState = useRouterState();
  const isAppRoute =
    routerState.location.pathname === "/" ||
    routerState.location.pathname.startsWith("/app-details");
  const isConnectorRoute =
    routerState.location.pathname.startsWith("/connectors");
  const isChatRoute = routerState.location.pathname === "/chat";
  const isSettingsRoute = routerState.location.pathname.startsWith("/settings");

  let selectedItem: string | null = null;
  if (hoverState === "start-hover:app") {
    selectedItem = "apps";
  } else if (hoverState === "start-hover:connector") {
    selectedItem = "connectors";
  } else if (hoverState === "start-hover:chat") {
    selectedItem = "chat";
  } else if (hoverState === "start-hover:settings") {
    selectedItem = "settings";
  } else if (state === "expanded") {
    if (isAppRoute) {
      selectedItem = "apps";
    } else if (isConnectorRoute) {
      selectedItem = "connectors";
    } else if (isChatRoute) {
      selectedItem = "chat";
    } else if (isSettingsRoute) {
      selectedItem = "settings";
    }
  }

  return (
    <Sidebar
      collapsible="icon"
      onMouseLeave={() => {
        if (!isDropdownOpen) {
          setHoverState("clear-hover");
        }
      }}
    >
      <SidebarContent className="overflow-hidden">
        <div className="flex mt-8">
          {/* Left Column: Menu items */}
          <div className="">
            <SidebarTrigger
              onMouseEnter={() => {
                setHoverState("clear-hover");
              }}
            />
            <AppIcons onHoverChange={setHoverState} />
          </div>
          {/* Right Column: Chat List Section */}
          <div className="w-[272px]">
            <AppList show={selectedItem === "apps"} />
            <ConnectorList show={selectedItem === "connectors"} />
            <ChatList show={selectedItem === "chat"} />
            <SettingsList show={selectedItem === "settings"} />
          </div>
        </div>
      </SidebarContent>

      <SidebarFooter>
        <SidebarMenu>
          <SidebarMenuItem>
            {/* Change button to open dialog instead of linking */}
            <SidebarMenuButton
              size="sm"
              className="font-medium w-14 flex flex-col items-center gap-1 h-14 mb-2 rounded-2xl"
              onClick={() => setIsHelpDialogOpen(true)} // Open dialog on click
            >
              <HelpCircle className="h-5 w-5" />
              <span className={"text-xs"}>{t("home:sidebar.help")}</span>
            </SidebarMenuButton>
            <HelpDialog
              isOpen={isHelpDialogOpen}
              onClose={() => setIsHelpDialogOpen(false)}
            />
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarFooter>

      <SidebarRail />
    </Sidebar>
  );
}

function AppIcons({
  onHoverChange,
}: {
  onHoverChange: (state: HoverState) => void;
}) {
  const { t } = useTranslation(["home", "chat", "settings"]);
  const routerState = useRouterState();
  const pathname = routerState.location.pathname;

  return (
    // When collapsed: only show the main menu
    <SidebarGroup className="pr-0">
      {/* <SidebarGroupLabel>Dyad</SidebarGroupLabel> */}

      <SidebarGroupContent>
        <SidebarMenu>
          {items.map((item) => {
            const isActive =
              (item.to === "/" && pathname === "/") ||
              (item.to !== "/" && pathname.startsWith(item.to));

            const label =
              item.key === "apps"
                ? t("home:sidebar.apps")
                : item.key === "connectors"
                  ? t("home:sidebar.connectors")
                  : item.key === "chat"
                    ? t("home:sidebar.chat")
                    : t("settings:title");

            return (
              <SidebarMenuItem key={item.key}>
                <SidebarMenuButton
                  as={Link}
                  to={item.to}
                  size="sm"
                  className={`font-medium w-14 flex flex-col items-center gap-1 h-14 mb-2 rounded-2xl ${
                    isActive ? "bg-sidebar-accent" : ""
                  }`}
                  onMouseEnter={() => {
                    if (item.key === "apps") {
                      onHoverChange("start-hover:app");
                    } else if (item.key === "connectors") {
                      onHoverChange("start-hover:connector");
                    } else if (item.key === "chat") {
                      onHoverChange("start-hover:chat");
                    } else if (item.key === "settings") {
                      onHoverChange("start-hover:settings");
                    }
                  }}
                >
                  <div className="flex flex-col items-center gap-1">
                    <item.icon className="h-5 w-5" />
                    <span className={"text-xs"}>{label}</span>
                  </div>
                </SidebarMenuButton>
              </SidebarMenuItem>
            );
          })}
        </SidebarMenu>
      </SidebarGroupContent>
    </SidebarGroup>
  );
}
