'use client';

import { useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { 
  LayoutDashboard, ShieldCheck, Settings, 
  ChevronLeft, ChevronRight, Briefcase, LogOut,
  Building2, FilePieChart, ChevronDown, LucideIcon,
  User2Icon, Cog, Blocks, Ticket, ReceiptText, UserCog2Icon, Store, GraduationCap
} from 'lucide-react';
import { cn } from '@/utils/cn';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { toggleSidebar } from '@/features/theme/themeSlice';
import { useAuthorization } from '@/features/auth/guards';
import { PERMISSIONS } from '@/constants/permissions';

interface SidebarSubItem {
  href: string;
  label: string;
  permission?: any; 
}

interface SidebarItem {
  type: 'link' | 'dropdown';
  label: string;
  icon: LucideIcon;
  href?: string;                  
  permission?: any;     
  children?: SidebarSubItem[];    
}

// 1. Standard Territory DSO Navigation Schema
const DSO_TERRITORY_NAVIGATION: SidebarItem[] = [
  { type: 'link', label: 'DSO Matrix Dashboard', icon: LayoutDashboard, href: '/dashboard' },
  { type: 'link', label: 'Coupons Management', icon: Ticket, href: '/coupons', permission: PERMISSIONS.COUPONS_MANAGE },
  { type: 'link', label: 'Purchase Management', icon: ReceiptText, href: '/purchase-orders', permission: PERMISSIONS.PURCHASE_ORDERS_READ },
  {
    type: 'dropdown',
    label: 'Territory Masters',
    icon: Building2,
    children: [
      { href: '/institutes', label: 'Institute Matrix', permission: PERMISSIONS.MASTERS_INSTITUTES_MANAGE },
      // { href: '/sectors', label: 'Sector Matrix', permission: PERMISSIONS.MASTERS_DISTRICTS_MANAGE },
    ]
  },
  { type: 'link', label: 'Analytical Reports', icon: FilePieChart, href: '/reports', permission: PERMISSIONS.REPORTS_EXPORT },
  { 
    type: 'link', 
    label: 'User Settings', 
    icon: UserCog2Icon, 
    href: '/user-settings', 
    permission: PERMISSIONS.REPORTS_EXPORT 
  },
];

// 2. Direct Reseller Mode Navigation Schema
const DSO_RESELLER_NAVIGATION: SidebarItem[] = [
  { type: 'link', label: 'Reseller Dashboard', icon: Store, href: '/dashboard' },
  // { type: 'link', label: 'My Self Storage', icon: Ticket, href: '/coupons' },
  { type: 'link', label: 'Direct Purchases', icon: ReceiptText, href: '/purchase-orders' },
  // { type: 'link', label: 'Student Admissions', icon: GraduationCap, href: '/students' },
];

// 3. Direct Institute Mode Navigation Schema
const DSO_INSTITUTE_NAVIGATION: SidebarItem[] = [
  { type: 'link', label: 'Institute Terminal', icon: Building2, href: '/dashboard' },
  { type: 'link', label: 'Career Advisors', icon: ShieldCheck, href: '/career-advisor' },
  // { type: 'link', label: 'Coupons Inventory', icon: Ticket, href: '/coupons' },
  { type: 'link', label: 'Purchase Orders', icon: ReceiptText, href: '/purchase-orders' },
];

// Default System Navigation
const DEFAULT_NAVIGATION_SCHEMA: SidebarItem[] = [
  // { type: 'link', label: 'Dashboard', icon: LayoutDashboard, href: '/dashboard' },
  // { type: 'link', label: 'Coupons Management', icon: Ticket, href: '/coupons', permission: PERMISSIONS.COUPONS_MANAGE },
  // { type: 'link', label: 'Purchase Management', icon: ReceiptText, href: '/purchase-orders', permission: PERMISSIONS.PURCHASE_ORDERS_READ },
  // {
  //   type: 'dropdown',
  //   label: 'Ecosystem Masters',
  //   icon: Building2,
  //   children: [
  //     { href: '/owners', label: 'Territory Owner Matrix', permission: PERMISSIONS.MASTERS_DISTRICTS_MANAGE },
  //     { href: '/states', label: 'State Matrix', permission: PERMISSIONS.MASTERS_DISTRICTS_MANAGE },
  //     { href: '/districts', label: 'District Matrix', permission: PERMISSIONS.MASTERS_DISTRICTS_MANAGE },
  //     { href: '/sectors', label: 'Sector Matrix', permission: PERMISSIONS.MASTERS_DISTRICTS_MANAGE },
  //     { href: '/institutes', label: 'Institute Matrix', permission: PERMISSIONS.MASTERS_INSTITUTES_MANAGE },
  //   ]
  // },
  // { type: 'link', label: 'Analytical Reports', icon: FilePieChart, href: '/reports', permission: PERMISSIONS.REPORTS_EXPORT },
  // { type: 'link', label: 'User Settings', icon: UserCog2Icon, href: '/user-settings' },

  { 
    type: 'link', 
    label: 'Dashboard', 
    icon: LayoutDashboard, 
    href: '/dashboard', 
    permission: null 
  },
  { 
    type: 'link', 
    label: 'Coupons Management', 
    icon: Ticket, 
    href: '/coupons', 
    permission: PERMISSIONS.COUPONS_MANAGE 
  },
  { 
    type: 'link', 
    label: 'Purchase Management', 
    icon: ReceiptText, 
    href: '/purchase-orders', 
    permission: PERMISSIONS.PURCHASE_ORDERS_READ 
  },
  {
    type: 'dropdown',
    label: 'Ecosystem Masters',
    icon: Building2,
    children: [
      { href: '/owners', label: 'Territory Owner Matrix', permission: PERMISSIONS.MASTERS_DISTRICTS_MANAGE },
      { href: '/states', label: 'State Matrix', permission: PERMISSIONS.MASTERS_DISTRICTS_MANAGE },
      { href: '/districts', label: 'District Matrix', permission: PERMISSIONS.MASTERS_DISTRICTS_MANAGE },
      { href: '/sectors', label: 'Sector Matrix', permission: PERMISSIONS.MASTERS_DISTRICTS_MANAGE },
      { href: '/institutes', label: 'Institute Matrix', permission: PERMISSIONS.MASTERS_INSTITUTES_MANAGE },
    ]
  },
  { 
    type: 'dropdown', 
    label: 'Career Advisor Control', 
    icon: ShieldCheck, 
    href: '/career-advisor', 
    permission: PERMISSIONS.ADVISORS_READ,
    children: [
      { href: '/career-advisor', label: ' Advisor Management', permission: PERMISSIONS.ADVISORS_READ },
    ]
  },
  { 
    type: 'dropdown', 
    label: 'Users', 
    icon: User2Icon, 
    permission: PERMISSIONS.ROLES_READ,
    children: [
      { href: '/users', label: 'User Management', permission: PERMISSIONS.ROLES_READ },
      { href: '/pending-approvals', label: 'Pending Approvals', permission: PERMISSIONS.ROLES_READ },
    ]
  },
  { 
    type: 'dropdown', 
    label: 'Access Control', 
    icon: Cog, 
    permission: PERMISSIONS.ROLES_READ,
    children: [
      { href: '/roles', label: 'Access Mtrix', permission: PERMISSIONS.ROLES_READ },
      { href: '/users-role', label: 'Roles Matrix', permission: PERMISSIONS.ROLES_READ },
    ]
  },
  { 
    type: 'dropdown', 
    label: 'LMS Control', 
    icon: Blocks, 
    permission: PERMISSIONS.ROLES_READ,
    children: [
      { href: '/lms/create', label: 'Orientation Mtrix', permission: PERMISSIONS.ROLES_READ },
      { href: '/courses', label: 'Courses', permission: PERMISSIONS.MASTERS_COURSES_MANAGE },
      { href: '/lms', label: 'My Onboarding', permission: PERMISSIONS.LMS_TRAINING_ACCESS },
    ]
  },
  { 
    type: 'link', 
    label: 'Analytical Reports', 
    icon: FilePieChart, 
    href: '/reports', 
    permission: PERMISSIONS.REPORTS_EXPORT 
  },
  { 
    type: 'link', 
    label: 'System Settings', 
    icon: Settings, 
    href: '/settings', 
    permission: PERMISSIONS.SETTINGS_MANAGE 
  },
  { 
    type: 'link', 
    label: 'User Settings', 
    icon: UserCog2Icon, 
    href: '/user-settings', 
    permission: PERMISSIONS.REPORTS_EXPORT 
  },
];

export function Sidebar() {
  const pathname = usePathname();
  const dispatch = useAppDispatch();
  const collapsed = useAppSelector((s) => s.ui.sidebarCollapsed);
  const activeDsoMode = useAppSelector((s) => s.ui.dsoWorkspaceMode);
  const { hasPermission, user } = useAuthorization();

  // Dynamic schema selection based on role and active workspace perspective
  const getNavigationSchema = (): SidebarItem[] => {
    if (user?.role === 'DISTRICT_SECTOR_OWNER') {
      if (activeDsoMode === 'RESELLER') return DSO_RESELLER_NAVIGATION;
      if (activeDsoMode === 'INSTITUTE') return DSO_INSTITUTE_NAVIGATION;
      return DSO_TERRITORY_NAVIGATION;
    }
    return DEFAULT_NAVIGATION_SCHEMA;
  };

  const activeSchema = getNavigationSchema();
  const isItemActive = (href: string) => pathname === href || pathname.startsWith(`${href}/`);

  const [openDropdowns, setOpenDropdowns] = useState<Record<string, boolean>>({});

  const toggleDropdown = (label: string) => {
    setOpenDropdowns((prev) => ({ ...prev, [label]: !prev[label] }));
  };

  return (
    <aside 
      className={cn(
        'relative flex h-screen flex-col border-r border-border/40 bg-surface transition-all duration-300 ease-in-out select-none',
        collapsed ? 'w-14' : 'w-56'
      )}
    >
      <button 
        onClick={() => dispatch(toggleSidebar())} 
        className="absolute -right-2.5 top-4 z-50 flex h-5 w-5 items-center justify-center rounded-full border border-border/60 bg-background text-muted-foreground hover:text-foreground transition-transform cursor-pointer"
      >
        {collapsed ? <ChevronRight className="h-3 w-3" /> : <ChevronLeft className="h-3 w-3" />}
      </button>

      <div className={cn("flex h-14 items-center px-3.5 border-b border-border/20", collapsed && "justify-center px-0")}>
        <div className="flex items-center gap-2 overflow-hidden">
          <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-border/60 bg-muted/40 text-foreground">
            <Briefcase className="h-3.5 w-3.5" />
          </div>
          <span className={cn(
            "text-xs font-bold tracking-tight text-foreground whitespace-nowrap ml-0.5",
            collapsed ? "opacity-0 max-w-0 pointer-events-none" : "opacity-100 max-w-xs"
          )}>
            Smart Skills India
          </span>
        </div>
      </div>

      <nav className="flex-1 space-y-0.5 px-2 py-3 overflow-y-auto">
        {activeSchema.map((navItem, index) => {
          if (navItem.type === 'link' && navItem.href) {
            if (navItem.permission && !hasPermission(navItem.permission)) return null;
            const active = isItemActive(navItem.href);
            
            return (
              <Link
                key={navItem.href}
                href={navItem.href}
                className={cn(
                  'group relative flex items-center rounded-lg py-2 text-xs font-medium transition-all',
                  collapsed ? 'justify-center px-0' : 'px-2.5 gap-2.5',
                  active ? 'bg-muted/70 text-foreground font-semibold' : 'text-muted-foreground hover:bg-muted/30 hover:text-foreground'
                )}
              >
                {active && <span className="absolute left-0 top-2 h-4 w-0.5 rounded-r bg-primary" />}
                <navItem.icon className={cn("h-4 w-4 shrink-0", active ? "text-primary" : "text-muted-foreground group-hover:text-foreground")} />
                {!collapsed && <span>{navItem.label}</span>}
              </Link>
            );
          }

          if (navItem.type === 'dropdown' && navItem.children) {
            const filteredChildren = navItem.children.filter(child => !child.permission || hasPermission(child.permission));
            if (filteredChildren.length === 0) return null;
            
            const isAnyChildActive = filteredChildren.some(child => isItemActive(child.href));
            const isExpanded = !!openDropdowns[navItem.label];

            return (
              <div key={`dropdown-${index}`} className="space-y-0.5">
                <button
                  onClick={() => !collapsed && toggleDropdown(navItem.label)}
                  className={cn(
                    'group w-full relative flex items-center rounded-lg py-2 text-xs font-medium transition-all text-left cursor-pointer',
                    collapsed ? 'justify-center px-0' : 'px-2.5 justify-between',
                    isAnyChildActive ? 'text-foreground font-semibold bg-muted/20' : 'text-muted-foreground hover:bg-muted/30 hover:text-foreground'
                  )}
                >
                  <div className="flex items-center gap-2.5">
                    <navItem.icon className={cn("h-4 w-4 shrink-0", isAnyChildActive ? "text-primary" : "text-muted-foreground group-hover:text-foreground")} />
                    {!collapsed && <span>{navItem.label}</span>}
                  </div>
                  {!collapsed && (
                    <ChevronDown className={cn("h-3 w-3 text-muted-foreground/60 transition-transform", isExpanded && "rotate-180")} />
                  )}
                </button>

                <div className={cn(!collapsed && isExpanded ? "block pl-6" : "hidden")}>
                  {filteredChildren.map((child) => (
                    <Link
                      key={child.href}
                      href={child.href}
                      className={cn(
                        'flex items-center rounded-lg py-1.5 text-[11px] font-medium transition-all px-2.5 hover:bg-muted/40',
                        isItemActive(child.href) ? 'text-primary font-bold bg-muted/20' : 'text-muted-foreground hover:text-foreground'
                      )}
                    >
                      <span>{child.label}</span>
                    </Link>
                  ))}
                </div>
              </div>
            );
          }

          return null;
        })}
      </nav>

      <div className="mt-auto border-t border-border/20 p-2">
        <div className="flex items-center justify-between p-1.5">
          <div className="flex items-center gap-2 overflow-hidden">
            <div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-primary/10 text-[10px] font-bold text-primary">
              {user?.name ? user.name.charAt(0).toUpperCase() : 'A'}
            </div>
            {!collapsed && (
              <div className="flex flex-col text-left">
                <span className="truncate text-[11px] font-semibold text-foreground">{user?.name}</span>
                <span className="truncate text-[9px] text-muted-foreground/60 uppercase font-mono">{activeDsoMode} Perspective</span>
              </div>
            )}
          </div>
        </div>
      </div>
    </aside>
  );
}