import { Link, useRouterState } from "@tanstack/react-router";
import {
  LayoutDashboard,
  Megaphone,
  Users,
  Sparkles,
  ShieldCheck,
  Wallet,
  BarChart3,
  Send,
  Settings,
  HelpCircle,
  Shield,
  Bell,
  Globe,
  Palette,
  ChevronRight,
} from "lucide-react";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  useSidebar,
} from "@/components/ui/sidebar";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { BrandLogo } from "./brand-logo";
import { WorkspaceSwitcher } from "./workspace-switcher";
import { Badge } from "@/components/ui/badge";

const main = [
  { title: "Dashboard", url: "/", icon: LayoutDashboard },
  { title: "Campaigns", url: "/campaigns", icon: Megaphone, badge: "12" },
  { title: "Audiences", url: "/audiences", icon: Users },
  { title: "AI Studio", url: "/ai-studio", icon: Sparkles, badge: "AI" },
  { title: "Channels", url: "/channels", icon: Send },
];

const ops = [
  { title: "Notifications", url: "/notifications", icon: Bell, badge: "3" },
  { title: "Compliance", url: "/compliance", icon: ShieldCheck },
  { title: "Analytics", url: "/analytics", icon: BarChart3 },
  { title: "Reports", url: "/reports", icon: BarChart3 },
  { title: "AI Insights", url: "/insights", icon: Sparkles },
  { title: "Wallet & Billing", url: "/wallet", icon: Wallet },
];

const platform = [
  { title: "Landing Page", url: "/home", icon: Globe },
  { title: "Superadmin", url: "/admin", icon: Shield },
];

const footer = [
  { title: "Settings", url: "/settings/profile", icon: Settings },
  { title: "Help", url: "/help", icon: HelpCircle },
];

export function AppSidebar() {
  const { state } = useSidebar();
  const collapsed = state === "collapsed";
  const pathname = useRouterState({ select: (r) => r.location.pathname });
  const isActive = (url: string) => (url === "/" ? pathname === "/" : pathname.startsWith(url));

  const renderItem = (item: {
    title: string;
    url: string;
    icon: typeof LayoutDashboard;
    badge?: string;
  }) => (
    <SidebarMenuItem key={item.title}>
      <SidebarMenuButton asChild isActive={isActive(item.url)} tooltip={item.title}>
        <Link to={item.url} className="flex items-center gap-2">
          <item.icon className="h-4 w-4" />
          {!collapsed && (
            <>
              <span className="flex-1">{item.title}</span>
              {item.badge && (
                <Badge
                  variant={item.badge === "AI" ? "default" : "secondary"}
                  className="h-4 px-1.5 text-[9px] font-semibold"
                >
                  {item.badge}
                </Badge>
              )}
            </>
          )}
        </Link>
      </SidebarMenuButton>
    </SidebarMenuItem>
  );

  return (
    <Sidebar collapsible="icon" className="border-r border-sidebar-border">
      <SidebarHeader className="gap-3 px-3 pt-4">
        <div className={collapsed ? "flex justify-center" : ""}>
          <BrandLogo collapsed={collapsed} />
        </div>
        {!collapsed && <WorkspaceSwitcher />}
      </SidebarHeader>

      <SidebarContent className="px-2">
        <SidebarGroup>
          {!collapsed && <SidebarGroupLabel>Workspace</SidebarGroupLabel>}
          <SidebarGroupContent>
            <SidebarMenu>{main.map(renderItem)}</SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>

        <SidebarGroup>
          {!collapsed && <SidebarGroupLabel>Operations</SidebarGroupLabel>}
          <SidebarGroupContent>
            <SidebarMenu>{ops.map(renderItem)}</SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>

        <SidebarGroup>
          {!collapsed && <SidebarGroupLabel>Platform</SidebarGroupLabel>}
          <SidebarGroupContent>
            <SidebarMenu>{platform.map(renderItem)}</SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>

        <SidebarGroup>
          {!collapsed && <SidebarGroupLabel>Appearances</SidebarGroupLabel>}
          <SidebarGroupContent>
            <SidebarMenu>
              <Collapsible defaultOpen={isActive("/appearance")} className="group/collapsible">
                <SidebarMenuItem>
                  <CollapsibleTrigger asChild>
                    <SidebarMenuButton tooltip="Appearances">
                      <Palette className="h-4 w-4" />
                      {!collapsed && (
                        <>
                          <span className="flex-1">Appearances</span>
                          <ChevronRight className="h-3.5 w-3.5 transition-transform group-data-[state=open]/collapsible:rotate-90" />
                        </>
                      )}
                    </SidebarMenuButton>
                  </CollapsibleTrigger>
                  <CollapsibleContent>
                    <SidebarMenuSub>
                      <SidebarMenuSubItem>
                        <SidebarMenuSubButton asChild isActive={isActive("/appearance")}>
                          <Link to="/appearance">Theme Option</Link>
                        </SidebarMenuSubButton>
                      </SidebarMenuSubItem>
                    </SidebarMenuSub>
                  </CollapsibleContent>
                </SidebarMenuItem>
              </Collapsible>
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      </SidebarContent>

      <SidebarFooter className="px-2 pb-3">
        <SidebarMenu>{footer.map(renderItem)}</SidebarMenu>
        {!collapsed && (
          <div className="mt-2 rounded-lg border border-sidebar-border bg-gradient-to-br from-primary/10 via-accent/5 to-transparent p-3">
            <div className="text-[11px] font-semibold flex items-center gap-1.5">
              <Sparkles className="h-3 w-3 text-primary" /> AI Credits
            </div>
            <div className="mt-1 text-[10px] text-muted-foreground">8,420 / 10,000 used</div>
            <div className="mt-2 h-1.5 rounded-full bg-sidebar-accent overflow-hidden">
              <div className="h-full w-[84%] bg-gradient-to-r from-primary to-accent" />
            </div>
          </div>
        )}
      </SidebarFooter>
    </Sidebar>
  );
}
