"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  LayoutDashboard,
  Building2,
  Home,
  BookOpen,
  Newspaper,
  Megaphone,
  Users,
  Settings,
  Shield,
  BarChart3,
  ChevronDown,
  Globe,
} from "lucide-react";
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  SidebarFooter,
  useSidebar,
} from "@/components/ui/sidebar";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useAuth } from "@/lib/auth-context";
import { usePermissions } from "@/hooks/use-permissions";

type NavItem = {
  title: string;
  icon: React.ComponentType<{ className?: string }>;
  href?: string;
  roles?: string[];
  permissions?: string[];
  children?: { title: string; href: string; roles?: string[]; permissions?: string[] }[];
};

type NavGroup = {
  title: string;
  roles?: string[];
  permissions?: string[];
  items: NavItem[];
};

const navigation: NavGroup[] = [
  {
    title: "Overview",
    items: [
      {
        title: "Dashboard",
        href: "/dashboard",
        icon: LayoutDashboard,
      },
    ],
  },
  {
    title: "Content",
    roles: ["admin", "seller", "company", "advertiser"],
    permissions: ["create-listing", "create-company", "create-post", "create-article", "create-ad-campaign"],
    items: [
      {
        title: "Properties",
        icon: Home,
        roles: ["admin", "seller"],
        permissions: ["create-listing", "edit-listing"],
        children: [
          { title: "All Properties", href: "/dashboard/properties" },
          { title: "Categories", href: "/dashboard/properties/categories", roles: ["admin"] },
          { title: "Add Property", href: "/dashboard/properties/create" },
        ],
      },
      {
        title: "Companies",
        icon: Building2,
        roles: ["admin", "company"],
        permissions: ["create-company", "edit-company"],
        children: [
          { title: "All Companies", href: "/dashboard/companies" },
          { title: "Categories", href: "/dashboard/companies/categories", roles: ["admin"] },
          { title: "Add Company", href: "/dashboard/companies/create" },
        ],
      },
      {
        title: "Blog",
        icon: BookOpen,
        roles: ["admin"],
        permissions: ["create-post", "edit-post", "publish-post"],
        children: [
          { title: "All Posts", href: "/dashboard/blog" },
          { title: "Categories", href: "/dashboard/blog/categories", roles: ["admin"] },
          { title: "Create Post", href: "/dashboard/blog/create" },
        ],
      },
      {
        title: "Magazine",
        icon: Newspaper,
        roles: ["admin"],
        permissions: ["manage-magazine-issues"],
        children: [
          { title: "Issues", href: "/dashboard/magazine/issues" },
          { title: "Subscriptions", href: "/dashboard/magazine/subscriptions", roles: ["admin"] },
        ],
      },
      {
        title: "Advertising",
        icon: Megaphone,
        roles: ["admin", "advertiser"],
        permissions: ["create-ad-campaign", "manage-ad-campaign"],
        children: [
          { title: "Ad Zones", href: "/dashboard/advertising/zones" },
          { title: "Advertisements", href: "/dashboard/advertising/ads" },
        ],
      },
    ],
  },
  {
    title: "Administration",
    roles: ["admin"],
    permissions: ["manage-users", "manage-site-settings"],
    items: [
      {
        title: "Reports & Analytics",
        href: "/dashboard/analytics",
        icon: BarChart3,
        roles: ["admin"],
      },
      {
        title: "Users",
        href: "/dashboard/users",
        icon: Users,
        roles: ["admin"],
        permissions: ["manage-users"],
      },
      {
        title: "Roles & Permissions",
        href: "/dashboard/roles",
        icon: Shield,
        roles: ["admin"],
        permissions: ["manage-users"],
      },
      {
        title: "Settings",
        href: "/dashboard/settings",
        icon: Settings,
      },
    ],
  },
];

export function AppSidebar() {
  const pathname = usePathname();
  const { user } = useAuth();
  const { hasAnyRole, hasPermission } = usePermissions();
  const { state } = useSidebar();
  const isCollapsed = state === "collapsed";

  const initials = user?.name
    ?.split(" ")
    .map((n) => n[0])
    .join("")
    .toUpperCase()
    .slice(0, 2) || "DP";

  // Check if user can see an item (role OR permission grants access)
  const canAccess = (item: { roles?: string[]; permissions?: string[] }) => {
    if (!item.roles && !item.permissions) return true;
    if (item.roles && hasAnyRole(item.roles)) return true;
    if (item.permissions && hasPermission(item.permissions)) return true;
    return false;
  };

  // Filter navigation based on user roles and permissions
  const filteredNavigation = navigation
    .filter((group) => canAccess(group))
    .map((group) => ({
      ...group,
      items: group.items
        .filter((item) => canAccess(item))
        .map((item) => {
          if (item.children) {
            return {
              ...item,
              children: item.children.filter((child) => canAccess(child)),
            };
          }
          return item;
        }),
    }))
    .filter((group) => group.items.length > 0);

  return (
    <Sidebar collapsible="icon" variant="sidebar">
      <SidebarHeader className="border-b border-sidebar-border">
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton size="lg" asChild>
              <Link href="/dashboard">
                <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary text-primary-foreground shadow-sm">
                  <Globe className="h-4 w-4" />
                </div>
                <div className="flex flex-col gap-0.5 leading-none">
                  <span className="font-display font-semibold">Diaspora Property</span>
                  <span className="text-xs text-muted-foreground">Admin Panel</span>
                </div>
              </Link>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarHeader>

      <SidebarContent>
        {filteredNavigation.map((group) => (
          <SidebarGroup key={group.title}>
            <SidebarGroupLabel>{group.title}</SidebarGroupLabel>
            <SidebarGroupContent>
              <SidebarMenu>
                {group.items.map((item) =>
                  item.children && item.children.length > 0 ? (
                    <CollapsibleNavItem
                      key={item.title}
                      item={item as { title: string; icon: React.ComponentType<{ className?: string }>; children: { title: string; href: string; roles?: string[]; permissions?: string[] }[] }}
                      pathname={pathname}
                      isCollapsed={isCollapsed}
                    />
                  ) : (
                    <SidebarMenuItem key={item.title}>
                      <SidebarMenuButton
                        asChild
                        isActive={pathname === (item.href ?? "")}
                        tooltip={item.title}
                      >
                        <Link href={item.href ?? "#"}>
                          <item.icon className="h-4 w-4" />
                          <span>{item.title}</span>
                        </Link>
                      </SidebarMenuButton>
                    </SidebarMenuItem>
                  )
                )}
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        ))}
      </SidebarContent>

      <SidebarFooter className="border-t border-sidebar-border">
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton size="lg" asChild>
              <Link href="/dashboard/settings">
                <Avatar className="h-8 w-8">
                  <AvatarImage src={user?.avatar || undefined} />
                  <AvatarFallback className="bg-primary/10 text-xs font-medium text-primary">
                    {initials}
                  </AvatarFallback>
                </Avatar>
                <div className="flex flex-col gap-0.5 leading-none">
                  <span className="text-sm font-medium">{user?.name}</span>
                  <span className="text-xs text-muted-foreground">{user?.email}</span>
                </div>
              </Link>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarFooter>
    </Sidebar>
  );
}

function CollapsibleNavItem({
  item,
  pathname,
  isCollapsed,
}: {
  item: {
    title: string;
    icon: React.ComponentType<{ className?: string }>;
    children: { title: string; href: string; roles?: string[]; permissions?: string[] }[];
  };
  pathname: string;
  isCollapsed: boolean;
}) {
  const isActive = item.children.some((child) => pathname.startsWith(child.href));

  return (
    <Collapsible defaultOpen={isActive} className="group/collapsible">
      <SidebarMenuItem>
        <CollapsibleTrigger asChild>
          <SidebarMenuButton tooltip={item.title} isActive={isActive}>
            <item.icon className="h-4 w-4" />
            <span>{item.title}</span>
            <ChevronDown className="ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-180" />
          </SidebarMenuButton>
        </CollapsibleTrigger>
        {!isCollapsed && (
          <CollapsibleContent>
            <SidebarMenuSub>
              {item.children.map((child) => (
                <SidebarMenuSubItem key={child.href}>
                  <SidebarMenuSubButton asChild isActive={pathname === child.href}>
                    <Link href={child.href}>
                      <span>{child.title}</span>
                    </Link>
                  </SidebarMenuSubButton>
                </SidebarMenuSubItem>
              ))}
            </SidebarMenuSub>
          </CollapsibleContent>
        )}
      </SidebarMenuItem>
    </Collapsible>
  );
}
