import { Avatar, AvatarFallback, AvatarImage } from "@/Components/UI/Avatar"
import { Button } from "@/Components/UI/Button"
import CreateWorkspaceModal from "@/Components/CreateWorkspaceModal"
import  SiteLogo  from "@/Components/UI/SiteLogo"
import { Zap, Calendar, Rocket, LineChart, Users, Settings, ChevronRight, Plus, Loader2, PanelLeftClose, PanelLeftOpen, FileText, BarChart3, UserCircle, Image } from "lucide-react"
import { Separator } from "@/Components/UI/Separator"
import { Link, usePage } from '@inertiajs/react'
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuSub,
  DropdownMenuSubTrigger,
  DropdownMenuSubContent,
} from "@/Components/UI/DropdownMenu"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/Components/UI/Tooltip"
import { router } from "@inertiajs/react";
import useTranslate from "@/hooks/useTranslate";
import useSidebarToggle from "@/hooks/useSidebarToggle";
import { useState, useEffect } from "react";
import { route } from "ziggy-js";


export default function SidebarNav({ onMobileClose }) {

  const { props } = usePage();
  const { auth, site_settings } = props;
  const { isCollapsed, toggle } = useSidebarToggle();
  const t = useTranslate();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isSwitching, setIsSwitching] = useState(false);
  const [switchingWorkspaceId, setSwitchingWorkspaceId] = useState(null);
  const [isAutoCollapsed, setIsAutoCollapsed] = useState(false);

  // Auto-collapse on medium screens
  useEffect(() => {
    const handleResize = () => {
      const isLargeScreen = window.innerWidth >= 1280; // xl breakpoint
      const isMediumScreen = window.innerWidth >= 768 && window.innerWidth < 1280; // md to lg

      if (isMediumScreen && !isAutoCollapsed) {
        setIsAutoCollapsed(true);
      } else if (isLargeScreen && isAutoCollapsed) {
        setIsAutoCollapsed(false);
      }
    };

    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [isAutoCollapsed]);

  const isSidebarCollapsed = isCollapsed || isAutoCollapsed;

  
  
  const navItems = [
    { name: t("Dashboard"), routeName: "user.home", icon: BarChart3 },
    { name: t("Platform"), routeName: "user.platform.index", icon: Zap },
    { name: t("Accounts"), routeName: "user.platform.account.index", icon: UserCircle },
    { name: t("All Posts"), routeName: "user.posts.index", icon: FileText },
    { name: t("Gallery"), routeName: "user.gallery.index", icon: Image },
    { name: t("Calendar"), routeName: "user.calender.index", icon: Calendar },
    { name: t("Campaign"), routeName: "user.campaign.index", icon: Rocket },
    { name: t("Analytics"), routeName: "user.analytics.index", icon: LineChart },
    { name: t("Access Control"), routeName: "user.access-control.index", icon: Users },
    { name: t("Settings"), routeName: "user.setting.index", icon: Settings },
  ];

  const openModal = () => {
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
  };

  const handleSwitchWorkspace = (workspaceId) => {
    if (isSwitching) return; // Prevent multiple clicks
    
    setIsSwitching(true);
    setSwitchingWorkspaceId(workspaceId);
    
    router.post(route("user.workspace.switch"), { id: workspaceId }, {
      onSuccess: () => {
        setIsSwitching(false);
        setSwitchingWorkspaceId(null);
        // Page will reload with new workspace context
      },
      onError: () => {
        setIsSwitching(false);
        setSwitchingWorkspaceId(null);
        // Could add toast error here
      }
    });
  };

  return (
   <>
       <TooltipProvider delayDuration={0}>
      <aside className={`${isSidebarCollapsed ? 'w-16' : 'w-64 sm:w-72'} bg-white h-screen flex flex-col dark:bg-zinc-900 transition-all duration-300 border-r border-gray-200 dark:border-zinc-800 relative z-[1]`}>
      
      {/* Toggle Button - Claude Style */}
      <div className="absolute lg:-right-14 -right-8 top-4 z-[10000]">
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              variant="ghost"
              size="sm"
              onClick={toggle}
              className="w-8 h-8 p-0 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-full shadow-sm hover:bg-gray-50 dark:hover:bg-zinc-800 transition-colors"
            >
              {isSidebarCollapsed ? (
                <PanelLeftOpen className="h-4 w-4 text-gray-600 dark:text-gray-400" />
              ) : (
                <PanelLeftClose className="h-4 w-4 text-gray-600 dark:text-gray-400" />
              )}
            </Button>
          </TooltipTrigger>
          <TooltipContent side="right">
            <p>{isSidebarCollapsed ? t("Expand sidebar") : t("Collapse sidebar")}</p>
          </TooltipContent>
        </Tooltip>
      </div>
      
      {/* Header with Logo */}
      <div className={`${isSidebarCollapsed ? 'px-2 py-4' : 'px-6 py-4'} transition-all duration-300`}>
        <div className={`${isSidebarCollapsed ? 'justify-center' : 'flex items-center gap-3'} flex`}>
          <SiteLogo
            src={props.site_logo || site_settings?.site_logo}
            siteName={site_settings?.site_name || props.site_name || "PostUno"}
            size={isSidebarCollapsed ? 32 : 36}
            variant="gradient"
            showText={!isSidebarCollapsed}
          />
          {!isSidebarCollapsed && (
            <div className="flex flex-col">
              <span className="text-lg font-bold text-gray-900 dark:text-white">
                {site_settings?.site_name || props.site_name || "PostUno"}
              </span>
              <span className="text-xs text-gray-500 dark:text-gray-400">
                Social Media Manager
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Navigation */}
      <nav className={`${isSidebarCollapsed ? 'px-2' : 'px-6'} flex flex-col space-y-1 flex-1`}>
        {navItems.map(({ name, routeName, icon: Icon }) => {
          const active = route().current(routeName)
          const navLink = (
            <Link
              key={name}
              href={route(routeName)}
              onClick={() => onMobileClose && onMobileClose()}
              className={`${isSidebarCollapsed ? 'justify-center px-2 py-3' : 'justify-start px-3 py-2.5'} flex items-center ${isSidebarCollapsed ? '' : 'gap-3'} rounded-lg transition-all duration-200 ${
                active
                  ? "bg-gradient-to-r from-primary to-secondary text-white shadow-sm"
                  : "text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-zinc-800 hover:text-gray-900 dark:hover:text-white"
              }`}
            >
              <Icon className={`${isSidebarCollapsed ? 'h-4 w-4' : 'h-5 w-5'} flex-shrink-0`} />
              {!isSidebarCollapsed && (
                <span className="font-medium text-sm">{name}</span>
              )}
            </Link>
          )

          if (isSidebarCollapsed) {
            return (
              <Tooltip key={name}>
                <TooltipTrigger asChild>
                  {navLink}
                </TooltipTrigger>
                <TooltipContent side="right" className="font-medium">
                  <p>{name}</p>
                </TooltipContent>
              </Tooltip>
            )
          }

          return navLink;
        })}
      </nav>

      {!isSidebarCollapsed && (
        <div className="px-6 mb-4">
          <Separator className="bg-gray-200 dark:bg-zinc-700" />
        </div>
      )}

      {/* Workspace Selector */}
      <div className={`${isSidebarCollapsed ? 'px-2' : 'px-6'} mt-auto mb-4`}>
        <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="ghost"
            disabled={isSwitching}
            className={`${
              isSidebarCollapsed
                ? 'w-12 h-12 p-0 justify-center'
                : 'w-full justify-start gap-3 px-3 py-2.5 h-auto'
            } text-white bg-gradient-to-br from-indigo-500 to-purple-600 hover:from-indigo-600 hover:to-purple-700 rounded-xl font-bold shadow-sm transition-all duration-200 ${isSwitching ? "opacity-75" : ""}`}
          >
            {isSidebarCollapsed ? (
              <div className="flex items-center justify-center">
                <span className="text-sm font-bold">
                  {auth?.user?.current_workspace?.name
                    ?.split(" ")
                    .map((n) => n[0])
                    .join("")
                    .toUpperCase() || "WS"}
                </span>
              </div>
            ) : (
              <>
                <Avatar className="h-8 w-8 rounded-lg bg-gradient-to-br from-indigo-500 to-purple-600">
                  <AvatarImage
                    src={auth?.user?.current_workspace?.logo || null}
                    alt={auth?.user?.current_workspace?.name}
                  />
                  <AvatarFallback className="bg-gradient-to-br from-indigo-500 to-purple-600 text-white font-bold text-xs rounded-lg">
                    {auth?.user?.current_workspace?.name
                      ?.split(" ")
                      .map((n) => n[0])
                      .join("")
                      .toUpperCase() || "WS"}
                  </AvatarFallback>
                </Avatar>
                <div className="flex-1 text-left">
                  <div className="text-sm font-semibold text-white">
                    {auth?.user?.current_workspace?.name}
                  </div>
                  <div className="text-xs text-indigo-200">
                    {t("Workspace")}
                  </div>
                </div>
                <ChevronRight className="h-4 w-4 text-indigo-200" />
              </>
            )}
          </Button>
        </DropdownMenuTrigger>

        <DropdownMenuContent side="right" align="end" className="w-64 bg-white">
          {/* Current Workspace */}
          <div className="flex items-center justify-between p-3">
            <div className="flex items-center space-x-3">
              <Avatar className="h-10 w-10 rounded-lg bg-gradient-to-br from-indigo-500 to-purple-600">
                <AvatarImage
                  src={auth?.user?.current_workspace?.logo || null}
                  alt={auth?.user?.current_workspace?.name}
                />
                <AvatarFallback className="bg-gradient-to-br from-indigo-500 to-purple-600 text-white font-bold text-sm rounded-lg">
                  <div className="flex flex-col items-center justify-center">
                    <svg className="w-4 h-4 mb-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-4m-5 0H3m2 0h4M9 7h6m-6 4h6m-6 4h6" />
                    </svg>
                    <span className="text-[10px]">
                      {auth?.user?.current_workspace?.name
                        ?.split(" ")
                        .map((n) => n[0])
                        .join("")
                        .toUpperCase() || "WS"}
                    </span>
                  </div>
                </AvatarFallback>
              </Avatar>
              <div>
                <div className="font-medium text-sm">
                  {auth?.user?.current_workspace?.name}
                </div>
                <div className="text-xs text-gray-500">
                  {auth?.user?.current_workspace?.email}
                </div>
              </div>
            </div>

            {/* Nested dropdown trigger */}
            <DropdownMenuSub>
              <DropdownMenuSubTrigger className="p-1">
                {/* <ChevronRight className="h-4 w-4 text-gray-500" /> */}
              </DropdownMenuSubTrigger>
              <DropdownMenuSubContent className="w-56 bg-white">
                <div className="px-2 py-1 text-xs uppercase text-gray-400">
                  Switch Workspace
                </div>
                {auth?.user?.workspaces?.map((workspace) => (
                  <DropdownMenuItem
                    key={workspace.id}
                    onClick={() => handleSwitchWorkspace(workspace.id)}
                    disabled={isSwitching}
                    className={`flex items-center space-x-2 p-2 rounded ${workspace.id === auth?.user?.current_workspace_id
                        ? "bg-gray-100 font-semibold text-black"
                        : "text-gray-500 hover:text-black hover:bg-gray-100"
                      } ${isSwitching && switchingWorkspaceId === workspace.id ? "opacity-50" : ""}`}
                  >
                    <Avatar className="h-6 w-6 rounded-lg">
                      <AvatarImage src="/placeholder.svg" alt={workspace.name} />
                      <AvatarFallback>
                        {workspace.name
                          ?.split(" ")
                          .map((n) => n[0])
                          .join("")
                          .toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <span className="flex-1">{workspace.name}</span>
                    {isSwitching && switchingWorkspaceId === workspace.id && (
                      <Loader2 className="h-4 w-4 animate-spin text-primary" />
                    )}
                  </DropdownMenuItem>
                ))}
              </DropdownMenuSubContent>
            </DropdownMenuSub>
          </div>

          <DropdownMenuSeparator />

          {/* Settings */}
          <DropdownMenuItem asChild>
            <Link
              href={route("user.workspace.settings")}
              className="flex items-center space-x-3 p-3 text-gray-500 hover:text-black hover:bg-gray-100 focus:bg-gray-100 no-underline"
            >
              <Settings className="h-4 w-4" />
              <span>Settings</span>
            </Link>
          </DropdownMenuItem>

          {/* Create New Workspace */}
          <DropdownMenuItem 
            onClick={openModal}
            className="flex items-center space-x-3 p-3 cursor-pointer text-gray-500 hover:text-black hover:bg-gray-100 focus:bg-gray-100 data-[highlighted]:bg-gray-100"
          >
            <Plus className="h-4 w-4" />
            <span>{t("Create new workspace")}</span>
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
      </div>

      

      </aside>
    </TooltipProvider>

    {/* Create Workspace Modal */}
      <CreateWorkspaceModal
        isOpen={isModalOpen}
        onClose={closeModal}
      />
   </>
  )
}
