/**
 * @module src/components/cortex/CortexSidebar
 * @audience installer
 * @layer frontend-component
 * @stability stable
 *
 * Sidebar for the Cortex internal operations application.
 */

import * as React from "react"
import { useNavigate, useLocation } from "react-router-dom"
import { useAuth } from "@core/contexts/AuthContext"
import { useAppPath } from "@core/hooks/useAppPath"
import {
  LayoutDashboard,
  Building2,
  Headphones,
  Users,
  BookOpen,
  GraduationCap,
  Handshake,
  Activity,
  Heart,
  BarChart3,
  Search,
  Download,
  UserPlus,
  ClipboardList,
  Bot,
  Upload,
  FolderGit2,
  GitGraph,
  SearchCode,
} from "lucide-react"
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarRail,
} from "@core/components/ui/sidebar"

export function CortexSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
  const navigate = useNavigate()
  const location = useLocation()
  const { user } = useAuth()
  const appPath = useAppPath()

  const isTeamAdmin =
    user?.is_system_admin ||
    user?.roles?.some((r: string) => r === 'support_admin' || r === 'system_admin')

  const crmItems = [
    { title: "Dashboard", url: appPath('/dashboard'), icon: LayoutDashboard },
    { title: "Accounts", url: appPath('/crm/accounts'), icon: Building2 },
    { title: "Contacts", url: appPath('/crm/contacts'), icon: Users },
    { title: "Deals", url: appPath('/crm/deals'), icon: Handshake },
    { title: "Health", url: appPath('/crm/health'), icon: Heart },
    { title: "Activity", url: appPath('/crm/activity'), icon: Activity },
  ]

  const opsItems = [
    { title: "Operations Dashboard", url: appPath('/operations'), icon: BarChart3 },
    { title: "Audit Funnel", url: appPath('/operations/audit-funnel'), icon: Search },
    { title: "Install Funnel", url: appPath('/operations/install-funnel'), icon: Download },
    { title: "Review Queue", url: appPath('/review-queue'), icon: ClipboardList },
    { title: "AI Dashboard", url: appPath('/ai-dashboard'), icon: Bot },
    { title: "Support", url: appPath('/support'), icon: Headphones },
    { title: "Community", url: appPath('/community'), icon: Users },
    { title: "Knowledge Base", url: appPath('/kb'), icon: BookOpen },
    { title: "KB Ingestion", url: appPath('/kb/ingestion'), icon: Upload },
    { title: "Courses", url: appPath('/courses'), icon: GraduationCap },
    { title: "Code Intelligence", url: appPath('/cil'), icon: FolderGit2 },
    { title: "CIL Search", url: appPath('/cil/search'), icon: SearchCode },
    { title: "CIL Agent", url: appPath('/cil/agent'), icon: Bot },
  ]

  const isActive = (url: string) => location.pathname.startsWith(url)

  return (
    <Sidebar {...props}>
      <SidebarHeader>
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton size="lg" onClick={() => navigate(appPath('/dashboard'))}>
              <div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-primary text-primary-foreground">
                <span className="text-sm font-bold">Cx</span>
              </div>
              <div className="flex flex-col gap-0.5 leading-none">
                <span className="font-semibold">Cortex</span>
                <span className="text-xs text-muted-foreground">Operations</span>
              </div>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarHeader>

      <SidebarContent>
        <SidebarGroup>
          <SidebarGroupLabel>CRM</SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu>
              {crmItems.map((item) => (
                <SidebarMenuItem key={item.title}>
                  <SidebarMenuButton
                    asChild
                    isActive={isActive(item.url)}
                  >
                    <a href={item.url}>
                      <item.icon className="h-4 w-4" />
                      <span>{item.title}</span>
                    </a>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              ))}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>

        <SidebarGroup>
          <SidebarGroupLabel>Operations</SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu>
              {opsItems.map((item) => (
                <SidebarMenuItem key={item.title}>
                  <SidebarMenuButton
                    asChild
                    isActive={isActive(item.url)}
                  >
                    <a href={item.url}>
                      <item.icon className="h-4 w-4" />
                      <span>{item.title}</span>
                    </a>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              ))}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      </SidebarContent>

      {isTeamAdmin && (
        <SidebarGroup>
          <SidebarGroupLabel>Admin</SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu>
              <SidebarMenuItem>
                <SidebarMenuButton asChild isActive={isActive(appPath('/team'))}>
                  <a href={appPath('/team')}>
                    <UserPlus className="h-4 w-4" />
                    <span>Team</span>
                  </a>
                </SidebarMenuButton>
              </SidebarMenuItem>
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      )}

      <SidebarFooter className="p-4">
        <div className="text-xs text-muted-foreground truncate">{user?.email || ''}</div>
      </SidebarFooter>

      <SidebarRail />
    </Sidebar>
  )
}
