import { Link } from '@tanstack/react-router';
import { Home, Settings, Construction, ChevronDown, ChevronRight, Building2, Database, BookOpen, CreditCard, Tag } from 'lucide-react';
import { cn } from '@/lib/utils';
import { DashboardUserProfile } from './DashboardUserProfile';
import { NotificationIndicator, LanguageSwitcher } from '@/components/shared';
import { NotificationUrgency, NotificationMessageType } from '@domain/entities';
import { useState, useMemo } from 'react';
import { LogoMinimised } from '@archer/ui/components';
import { useTranslation } from '@/i18n/TranslationProvider';
import { useChannel } from '@/presentation/hooks';
import { Channel } from '@archer/domain';

/**
 * Sidebar Component
 *
 * Left sidebar navigation for the dashboard with:
 * - TWWIM branding at top
 * - Notification indicator
 * - Navigation links with icons
 * - Active state highlighting
 * - Hover effects with TWWIM primary color
 * - Dark slate background (slate-800)
 */

interface SidebarProps {
  className?: string;
  unreadCount?: number;
  highestUrgency?: NotificationUrgency;
  messageType?: NotificationMessageType;
  onNotificationClick?: () => void;
}

interface NavigationItem {
  name: string;
  key?: string;
  to?: string;
  icon: React.ComponentType<{ className?: string; size?: number }>;
  exactMatch?: boolean;
  submenu?: NavigationItem[];
}

const isDev = import.meta.env.DEV;

export function Sidebar({
  className,
  unreadCount = 0,
  highestUrgency = NotificationUrgency.LOW,
  messageType = NotificationMessageType.INFO,
  onNotificationClick = () => {},
}: SidebarProps) {
  const { t } = useTranslation();
  const channel = useChannel();

  const navigation: NavigationItem[] = useMemo(() => {
    // Per-channel UI shape:
    //   - Tenants list: WP plugin embeds a single site, hide the multi-tenant
    //     CRUD list there. Web + Shopify deep-link can manage multiple.
    //   - Subscription / Promotions: Shopify merchants pay through Shopify's
    //     billing API, hide the TWWIM-billing surfaces. WP + Web see them
    //     because billing is direct-to-TWWIM.
    const showTenants = channel !== Channel.WORDPRESS;
    const showBillingSurfaces = channel !== Channel.SHOPIFY;

    return [
      { name: t('nav.dashboard'), to: '/dashboard', icon: Home, exactMatch: true },
      ...(showTenants ? [{ name: t('nav.tenants'), to: '/dashboard/tenants', icon: Building2 }] : []),
      { name: t('nav.knowledge'), to: '/dashboard/knowledge', icon: BookOpen },
      ...(showBillingSurfaces ? [
        { name: t('nav.subscription'), to: '/dashboard/subscription', icon: CreditCard },
        { name: t('nav.promotions'), to: '/dashboard/promotions', icon: Tag },
      ] : []),
      ...(isDev ? [{
        name: t('nav.wip'),
        key: 'wip',
        icon: Construction,
        submenu: [
          { name: t('nav.infoCenter'), to: '/dashboard/info-center', icon: Database },
          { name: t('nav.settings'), to: '/dashboard/settings', icon: Settings },
        ],
      }] : []),
    ];
  }, [t, channel]);

  // Initialize "Work In Progress" menu as expanded by default
  const [expandedMenus, setExpandedMenus] = useState<Set<string>>(new Set(['wip']));

  const toggleMenu = (name: string) => {
    setExpandedMenus((prev) => {
      const next = new Set(prev);
      if (next.has(name)) {
        next.delete(name);
      } else {
        next.add(name);
      }
      return next;
    });
  };

  const renderNavItem = (item: NavigationItem, isSubmenu = false) => {
    const hasSubmenu = item.submenu && item.submenu.length > 0;
    const trackingKey = item.key || item.name;
    const isExpanded = expandedMenus.has(trackingKey);
    const Icon = item.icon;

    if (hasSubmenu) {
      // Expandable menu item
      return (
        <div key={trackingKey}>
          <button
            onClick={() => toggleMenu(trackingKey)}
            className="w-full flex items-center gap-3 px-4 py-3 text-slate-50 hover:bg-primary/20 hover:text-primary rounded-lg transition-all duration-150"
          >
            <Icon className="h-5 w-5" />
            <span className="flex-1 text-left font-medium">{item.name}</span>
            {isExpanded ? (
              <ChevronDown size={16} className="text-slate-400" />
            ) : (
              <ChevronRight size={16} className="text-slate-400" />
            )}
          </button>
          {isExpanded && (
            <div className="ml-4 mt-1 space-y-1">
              {item.submenu!.map((subItem) => renderNavItem(subItem, true))}
            </div>
          )}
        </div>
      );
    }

    // Regular link item
    return (
      <Link
        key={trackingKey}
        to={item.to!}
        className={`flex items-center gap-3 px-4 py-3 rounded-lg text-slate-50 hover:bg-primary/20 hover:text-primary transition-all duration-150 group ${
          isSubmenu ? 'text-sm' : ''
        }`}
        activeOptions={item.exactMatch ? { exact: true } : undefined}
        activeProps={{
          className: 'bg-primary/20 text-primary font-medium'
        }}
      >
        <Icon className="h-5 w-5 group-hover:scale-110 transition-transform" />
        <span className="font-medium">{item.name}</span>
      </Link>
    );
  };

  return (
    <aside
      className={cn(
        'w-72 bg-sidebar text-slate-50 flex flex-col border-r border-sidebar-border',
        className
      )}
    >
      {/* TWWIM Branding */}
      <div className="flex items-center justify-center px-4 py-5 border-b border-sidebar-border">
        <LogoMinimised variant="green" className="h-10 w-auto" />
      </div>

      {/* Notification Indicator - Always Visible */}
      {onNotificationClick && (
        <div className="border-b border-sidebar-border">
          <NotificationIndicator
            unreadCount={unreadCount}
            highestUrgency={highestUrgency}
            messageType={messageType}
            onClick={onNotificationClick}
          />
        </div>
      )}

      {/* Navigation Links */}
      <nav className="flex-1 min-h-0 overflow-y-auto p-4 space-y-1">
        {navigation.map((item) => renderNavItem(item))}
      </nav>

      {/* Language Switcher */}
      <div className="px-4 py-2 border-t border-sidebar-border">
        <LanguageSwitcher />
      </div>

      {/* User Profile */}
      <div className="mt-auto border-t border-sidebar-border p-4">
        <DashboardUserProfile />
      </div>
    </aside>
  );
}
