import React, { useState, useRef, useEffect } from 'react';
import { usePathname, useSearchParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import * as Tooltip from '@radix-ui/react-tooltip';
import { ChevronLeft, ExternalLink } from 'lucide-react';
import { getAppVersion } from '@alga-psa/core';
import { CollapseToggleButton } from '@alga-psa/ui/components/CollapseToggleButton';
import { DynamicNavigationSlot } from '@alga-psa/ui/components/extensions/DynamicNavigationSlot';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';
import {
  menuItems as defaultMenuItems,
  bottomMenuItems as defaultBottomMenuItems,
  navigationSections as defaultNavigationSections,
  settingsNavigationSections,
  billingNavigationSections,
  extensionsNavigationSections,
  type NavigationSection,
  type NavMode,
} from '@/config/menuConfig';
import SidebarMenuItem from './SidebarMenuItem';
import SidebarSubMenuItem from './SidebarSubMenuItem';
import SidebarBottomMenuItem from './SidebarBottomMenuItem';
import GitHubStarButton from './GitHubStarButton';
import SearchPalette from '@/components/search/SearchPalette';
import type { MenuItem } from '@/config/menuConfig';
import { useUserPreference } from '@alga-psa/user-composition/hooks';

interface SidebarProps {
  sidebarOpen: boolean;
  setSidebarOpen: React.Dispatch<React.SetStateAction<boolean>>;
  menuItems?: MenuItem[];
  bottomMenuItems?: MenuItem[];
  menuSections?: NavigationSection[];
  disableTransition?: boolean;
  mode?: NavMode;
  onBackToMain?: () => void;
  onMenuItemClick?: (href?: string) => void;
  appDisplayName?: string;
  appLogoAlt?: string;
  settingsSectionsOverride?: NavigationSection[];
}

const Sidebar: React.FC<SidebarProps> = ({
  sidebarOpen,
  setSidebarOpen,
  menuItems = defaultMenuItems,
  bottomMenuItems = defaultBottomMenuItems,
  menuSections,
  disableTransition = false,
  mode = 'main',
  onBackToMain,
  onMenuItemClick,
  appDisplayName = 'AlgaPSA',
  appLogoAlt = 'AlgaPSA Logo',
  settingsSectionsOverride,
}): React.JSX.Element => {
  const appVersion = getAppVersion();
  const { t } = useTranslation('msp/core');
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const router = useRouter();
  const [openSubmenu, setOpenSubmenu] = useState<string | null>(null);

  // Track mode changes for transition animation
  const prevModeRef = useRef<NavMode>(mode);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const [transitionDirection, setTransitionDirection] = useState<'in' | 'out'>('in');

  useEffect(() => {
    if (prevModeRef.current !== mode) {
      // Mode has changed - trigger transition animation
      setTransitionDirection('out');
      setIsTransitioning(true);

      // After the exit animation, switch direction for enter animation
      const exitTimer = setTimeout(() => {
        setTransitionDirection('in');
      }, 150);

      // Complete the transition
      const enterTimer = setTimeout(() => {
        setIsTransitioning(false);
        prevModeRef.current = mode;
      }, 400);

      return () => {
        clearTimeout(exitTimer);
        clearTimeout(enterTimer);
      };
    }
  }, [mode]);

  const isSettingsMode = mode === 'settings';
  const isBillingMode = mode === 'billing';
  const isExtensionsMode = mode === 'extensions';
  const isSubMode = isSettingsMode || isBillingMode || isExtensionsMode;

  const isActive = (path: string) => {
    if (!path) {
      return false;
    }

    const [targetPath, queryString] = path.split('?');

    if (pathname !== targetPath) {
      return false;
    }

    if (!queryString) {
      // For settings mode, if no tab param in target, match when current URL also has no tab
      if (isSettingsMode && targetPath === '/msp/settings') {
        return !searchParams?.get('tab') || searchParams?.get('tab') === 'general';
      }
      // For billing mode, if no tab param in target, match when current URL also has no tab
      if (isBillingMode && targetPath === '/msp/billing') {
        return !searchParams?.get('tab') || searchParams?.get('tab') === 'contracts';
      }
      return true;
    }

    const targetParams = new URLSearchParams(queryString);
    const targetTab = targetParams.get('tab');

    if (!targetTab) {
      return true;
    }

    return searchParams?.get('tab') === targetTab;
  };

  const toggleSubmenu = (name: string) => {
    setOpenSubmenu(openSubmenu === name ? null : name);
  };

  const handleBackToMain = () => {
    if (onBackToMain) {
      onBackToMain();
    } else {
      // Fallback to navigation if no callback provided
      router.push('/msp/dashboard');
    }
  };

  const translateMenuItem = (item: MenuItem): MenuItem => ({
    ...item,
    name: item.translationKey ? t(item.translationKey, { defaultValue: item.name }) : item.name,
    subItems: item.subItems?.map(translateMenuItem),
  });

  const translateSection = (section: NavigationSection): NavigationSection => ({
    ...section,
    title: section.translationKey ? t(section.translationKey, { defaultValue: section.title }) : section.title,
    items: section.items.map(translateMenuItem),
  });

  const renderMenuItem = (item: MenuItem) => {
    if (sidebarOpen) {
      return (
        <li key={item.name}>
          <SidebarMenuItem
            id={`menu-${item.name.toLowerCase().replace(/\s+/g, '-')}`}
            item={item}
            isActive={isActive}
            sidebarOpen={sidebarOpen}
            openSubmenu={openSubmenu}
            onToggleSubmenu={toggleSubmenu}
            onMenuItemClick={onMenuItemClick}
          />
          {item.subItems && openSubmenu === item.name && (
            <ul className="ml-4 mt-2 space-y-1">
              {item.subItems.map((subItem: MenuItem): React.JSX.Element => (
                <li key={subItem.name}>
                  <SidebarSubMenuItem
                    item={subItem}
                    parentId={`menu-${item.name.toLowerCase().replace(/\s+/g, '-')}`}
                    isActive={isActive}
                    onMenuItemClick={onMenuItemClick}
                  />
                </li>
              ))}
            </ul>
          )}
        </li>
      );
    }

    return (
      <Tooltip.Provider delayDuration={300} key={item.name}>
        <Tooltip.Root>
          <Tooltip.Trigger asChild>
            <li>
              <SidebarMenuItem
                id={`menu-${item.name.toLowerCase().replace(/\s+/g, '-')}`}
                item={item}
                isActive={isActive}
                sidebarOpen={sidebarOpen}
                openSubmenu={openSubmenu}
                onToggleSubmenu={toggleSubmenu}
                onMenuItemClick={onMenuItemClick}
              />
              {item.subItems && openSubmenu === item.name && (
                <ul className="ml-4 mt-2 space-y-1">
                  {item.subItems.map((subItem: MenuItem): React.JSX.Element => (
                    <li key={subItem.name}>
                      <SidebarSubMenuItem
                        item={subItem}
                        parentId={`menu-${item.name.toLowerCase().replace(/\s+/g, '-')}`}
                        isActive={isActive}
                        onMenuItemClick={onMenuItemClick}
                      />
                    </li>
                  ))}
                </ul>
              )}
            </li>
          </Tooltip.Trigger>
          <Tooltip.Portal>
            <Tooltip.Content
              className="bg-subMenu-bg text-subMenu-text px-2 py-1 rounded-md text-sm"
              side="right"
              sideOffset={5}
            >
              {item.name}
              <Tooltip.Arrow style={{ fill: 'var(--color-submenu-bg)' }} />
            </Tooltip.Content>
          </Tooltip.Portal>
        </Tooltip.Root>
      </Tooltip.Provider>
    );
  };

  // Determine which sections to render based on mode
  const settingsSections: NavigationSection[] = settingsSectionsOverride ?? settingsNavigationSections;

  const billingSections: NavigationSection[] = billingNavigationSections;

  const rawSectionsToRender: NavigationSection[] = isSettingsMode
    ? settingsSections
    : isBillingMode
      ? billingSections
      : isExtensionsMode
        ? extensionsNavigationSections
        : (menuSections ?? defaultNavigationSections);

  const sectionsToRender = rawSectionsToRender.map(translateSection);
  const translatedBottomMenuItems = bottomMenuItems.map(translateMenuItem);
  const backToMainLabel = t('sidebar.backToMain', { defaultValue: 'Back to Main' });

  // Determine automation ID based on mode
  const sidebarAutomationId = isSettingsMode
    ? 'settings-sidebar'
    : isBillingMode
      ? 'billing-sidebar'
      : isExtensionsMode
        ? 'extensions-sidebar'
        : 'main-sidebar';

  return (
    <aside
      data-automation-id={sidebarAutomationId}
      className={`bg-sidebar-bg text-sidebar-text h-screen flex flex-col relative ${
        disableTransition ? '' : 'transition-all duration-300 ease-in-out'
      } ${sidebarOpen ? 'w-64' : 'w-16'}`}
      style={{ width: sidebarOpen ? '16rem' : '4rem' }}
    >
      <a
        href="/msp/dashboard"
        className="p-4 flex items-center space-x-2 hover:bg-white/10 cursor-pointer"
        aria-label={t('sidebar.goToDashboard', { defaultValue: 'Go to dashboard' })}
        id="logo-home-link"
      >
        <div className="w-8 h-8 bg-purple-600 rounded-full flex items-center justify-center overflow-hidden flex-shrink-0">
          <Image
            src="/images/avatar-purple-background.png"
            alt={t('sidebar.logoAlt', { defaultValue: appLogoAlt })}
            width={200}
            height={200}
            className="w-full h-full object-cover"
          />
        </div>
        <span className={`text-xl font-semibold truncate ${sidebarOpen ? '' : 'hidden'}`}>{appDisplayName}</span>
      </a>

      {/* Back to Main button - shown in settings and billing modes */}
      {isSubMode && (
        <div
          className={`px-2 py-2 transition-all duration-200 ease-out ${
            isTransitioning
              ? transitionDirection === 'out'
                ? 'opacity-0 translate-x-[-10px]'
                : 'opacity-100 translate-x-0'
              : 'opacity-100 translate-x-0'
          }`}
        >
          {sidebarOpen ? (
            <button
              id="settings-back-to-main-button"
              onClick={handleBackToMain}
              className="w-full px-3 py-2 flex items-center gap-2 text-base text-purple-400 hover:text-purple-300 hover:bg-white/10 rounded-md transition-colors"
            >
              <ChevronLeft className="h-5 w-5" />
              <span>{backToMainLabel}</span>
            </button>
          ) : (
            <Tooltip.Provider delayDuration={300}>
              <Tooltip.Root>
                <Tooltip.Trigger asChild>
                  <button
                    id="settings-back-to-main-button"
                    onClick={handleBackToMain}
                    className="w-full p-2 flex items-center justify-center text-purple-400 hover:text-purple-300 hover:bg-white/10 rounded-md transition-colors"
                  >
                    <ChevronLeft className="h-4 w-4" />
                  </button>
                </Tooltip.Trigger>
                <Tooltip.Portal>
                  <Tooltip.Content
                    className="bg-subMenu-bg text-subMenu-text px-2 py-1 rounded-md text-sm z-50"
                    side="right"
                    sideOffset={5}
                  >
                    {backToMainLabel}
                    <Tooltip.Arrow style={{ fill: 'var(--color-submenu-bg)' }} />
                  </Tooltip.Content>
                </Tooltip.Portal>
              </Tooltip.Root>
            </Tooltip.Provider>
          )}
        </div>
      )}

      <SearchPalette
        collapsed={!sidebarOpen}
        onCollapsedClick={() => setSidebarOpen(true)}
      />

      <nav className={`${isSubMode ? 'mt-0' : 'mt-1'} flex-grow min-h-0 overflow-y-auto overscroll-contain sidebar-nav`}>
        <div
          className={`transition-all duration-200 ease-out ${
            isTransitioning
              ? transitionDirection === 'out'
                ? 'opacity-0 translate-x-[-10px]'
                : 'opacity-100 translate-x-0'
              : 'opacity-100 translate-x-0'
          }`}
        >
        {sectionsToRender.map((section, sectionIndex) => (
          <div key={section.title || 'nav-section'} className="px-2">
            {sidebarOpen && section.title ? (
              <p className={`text-xs uppercase tracking-wide text-gray-400 px-2 mb-2 ${sectionIndex === 0 ? 'mt-0' : 'mt-6'}`} aria-label={section.title}>
                {section.title}
              </p>
            ) : (
              !sidebarOpen && section.title ? (
                <div className={`h-px bg-gray-700 ${sectionIndex === 0 ? 'mt-0 mb-3' : 'my-3'}`} aria-hidden="true" />
              ) : null
            )}
            <ul className="space-y-1">
              {section.items.map((item) => renderMenuItem(item))}
            </ul>
          </div>
        ))}
        {/* Extension navigation items - shown in extensions mode as installed extensions */}
        {isExtensionsMode && (
          <div className="mt-4 border-t border-gray-700 pt-4 px-2">
            <DynamicNavigationSlot collapsed={!sidebarOpen} />
          </div>
        )}
        </div>
      </nav>

      {/* Bottom menu items - only in main mode */}
      {!isSubMode && (
        <div
          className={`mt-auto transition-all duration-200 ease-out ${
            isTransitioning
              ? transitionDirection === 'out'
                ? 'opacity-0 translate-x-[-10px]'
                : 'opacity-100 translate-x-0'
              : 'opacity-100 translate-x-0'
          }`}
        >
          <ul className="space-y-1">
            {translatedBottomMenuItems.map((item): React.JSX.Element => (
              <li key={item.name}>
                <SidebarMenuItem
                  id={`bottom-menu-${item.name.toLowerCase().replace(/\s+/g, '-')}`}
                  item={item}
                  isActive={isActive}
                  sidebarOpen={sidebarOpen}
                  openSubmenu={openSubmenu}
                  onToggleSubmenu={toggleSubmenu}
                  onMenuItemClick={onMenuItemClick}
                />
                {item.subItems && openSubmenu === item.name && (
                  <ul className="ml-4 mt-2 space-y-1">
                    {item.subItems.map((subItem: MenuItem): React.JSX.Element => (
                      <li key={subItem.name}>
                        <SidebarSubMenuItem
                          item={subItem}
                          parentId={`bottom-menu-${item.name.toLowerCase().replace(/\s+/g, '-')}`}
                          isActive={isActive}
                          onMenuItemClick={onMenuItemClick}
                        />
                      </li>
                    ))}
                  </ul>
                )}
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Version info */}
      <div className="px-4 py-3 border-t border-gray-700">
        <div className="flex items-center justify-between">
          <a
            id="app-version-link"
            href="https://github.com/Nine-Minds/alga-psa/releases"
            target="_blank"
            rel="noopener noreferrer"
            className="text-xs text-gray-400 hover:text-gray-200 transition-colors flex items-center gap-1"
            title={sidebarOpen ? undefined : `Version ${appVersion}`}
          >
            {sidebarOpen ? (
              <>
                <span>v{appVersion}</span>
                <ExternalLink className="w-3 h-3" />
              </>
            ) : (
              <span className="text-[10px]">v{appVersion.split('.')[0]}.{appVersion.split('.')[1]}</span>
            )}
          </a>
          {sidebarOpen && <GitHubStarButton />}
        </div>
      </div>

      <CollapseToggleButton
        id="sidebar-toggle-button"
        isCollapsed={!sidebarOpen}
        collapsedLabel={t('sidebar.expandSidebar', { defaultValue: 'Expand sidebar' })}
        expandedLabel={t('sidebar.collapseSidebar', { defaultValue: 'Collapse sidebar' })}
        onClick={() => setSidebarOpen(!sidebarOpen)}
        className="absolute -right-3 top-12 z-10"
      />
    </aside>
  );
};

export default Sidebar;
