"use client";

import * as React from "react";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import {
  LayoutDashboard,
  Upload,
  ShieldCheck,
  Gauge,
  AlertTriangle,
  Users,
  Bot,
  Lightbulb,
  FileText,
  Settings,
  MapPin,
  Sparkles,
  TrendingUp,
  ClipboardList,
  Plug,
  Code2,
  CreditCard,
  Building2,
  CheckSquare,
  Rocket,
  Bell,
  Crosshair,
  Mail,
  Globe,
  Search,
  PenTool,
  FileSearch,
  Network,
  Link2,
  Unlink,
  X,
  Megaphone,
  Activity,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useUser } from "@clerk/nextjs";
import { useBrand } from "@/context/brand-context";
import { usePlanContext } from "@/context/plan-context";
import { planHasFeature, type FeatureKey } from "@/lib/plan-config";
import { SidebarTaskIndicator } from "@/components/sidebar-task-indicator";
import { Lock } from "lucide-react";

// href → FeatureKey map. Only protected pages are listed — anything
// absent is considered "always available" and renders without a
// lock icon or gate redirect. Keep in sync with the FeatureGate
// wrappers below and with PLANS in src/lib/plan-config.ts.
const PROTECTED_ROUTES: Record<string, FeatureKey> = {
  "/rank-tracker":          "rank_tracker",
  "/competitors":           "competitor_intel",
  "/ai-visibility":         "ai_visibility",
  "/backlinks":             "backlinks",
  "/industry-intel":        "industry_intel",
  "/schema-generator":      "schema_generator",
  "/report-studio":         "report_studio",
  "/content-brief":         "seo_content_brief",
  "/llmo-content-brief":    "llmo_content_brief",
  "/page-launch-tracker":   "page_launch_tracker",
  "/client-portal-setup":   "client_portal",
  "/email-reports":         "email_reports",
  "/writing-assistant":     "writing_assistant",
  "/topic-map":             "topic_map",
  "/paid-media":            "paid_media",
  "/ai-roi":                "ai_roi_dashboard",
  "/ai-recommendations":    "ai_recommendations",
};

type NavItem = { label: string; href: string; icon: React.ElementType; badge?: string };
type NavSection = { heading: string; items: NavItem[] };

const navSections: NavSection[] = [
  {
    heading: "Workspace",
    items: [
      { label: "Brands Hub",        href: "/brands-hub",      icon: Building2 },
      { label: "AI Strategist",     href: "/ai-strategist",   icon: Sparkles },
      { label: "Signals Center",    href: "/signals",         icon: Bell },
    ],
  },
  {
    heading: "Setup",
    items: [
      { label: "AI Website Intake", href: "/website-upload",  icon: Upload },
      { label: "Integrations",      href: "/integrations",    icon: Plug },
      { label: "Site Tag",           href: "/site-tag",        icon: Code2 },
    ],
  },
  {
    heading: "Intelligence",
    items: [
      { label: "Dashboard",         href: "/dashboard",                icon: LayoutDashboard },
      { label: "Live Sessions",      href: "/dashboard/live-sessions",   icon: Activity },
      { label: "Site Tag Analytics", href: "/site-tag-analytics",        icon: TrendingUp },
      { label: "Paid Media",        href: "/paid-media",               icon: Megaphone },
      { label: "AI Visibility",     href: "/ai-visibility",            icon: Bot },
      { label: "Keyword Research",  href: "/keyword-research",         icon: Search },
      { label: "Rank Tracker",      href: "/rank-tracker",             icon: Crosshair },
      { label: "Competitor Intel",   href: "/competitors",              icon: Users },
      { label: "Content Intel",    href: "/content-audit",            icon: FileSearch },
      { label: "Backlinks",          href: "/backlinks",                icon: Link2 },
      { label: "Industry Intel",    href: "/industry-intel",           icon: Globe },
      { label: "Local GEO",         href: "/local-geo",                icon: MapPin },
    ],
  },
  {
    heading: "LLMO",
    items: [
      { label: "AI Attribution",     href: "/site-tag-analytics?tab=ai", icon: Bot },
      { label: "AI ROI Dashboard",   href: "/ai-roi",                    icon: TrendingUp },
      { label: "AI Recommendations", href: "/ai-recommendations",        icon: Lightbulb },
    ],
  },
  {
    heading: "Technical",
    items: [
      { label: "Technical Audit",       href: "/technical-audit",          icon: ShieldCheck },
      { label: "Core Web Intelligence", href: "/site-performance-audit",   icon: Gauge },
      { label: "Broken Links",          href: "/broken-links",             icon: Unlink },
      { label: "Schema Generator",     href: "/schema-generator",         icon: Code2 },
    ],
  },
  {
    heading: "Content",
    items: [
      { label: "SEO Content Brief",  href: "/content-brief",       icon: FileText },
      { label: "LLMO Content Brief", href: "/llmo-content-brief",  icon: Bot },
      { label: "Writing Assistant",  href: "/writing-assistant",   icon: PenTool },
      { label: "Topic Map",         href: "/topic-map",            icon: Network },
    ],
  },
  {
    heading: "Execution",
    items: [
      { label: "Recommendations", href: "/recommendations",     icon: Lightbulb },
      { label: "Execution Hub",   href: "/execution-hub",        icon: CheckSquare },
      { label: "Launch Tracker",  href: "/page-launch-tracker",  icon: Rocket },
    ],
  },
  {
    heading: "Reporting",
    items: [
      { label: "Report Studio", href: "/report-studio", icon: ClipboardList },
      { label: "Email Reports", href: "/email-reports",  icon: Mail },
    ],
  },
  {
    heading: "System",
    items: [
      { label: "Client Portal", href: "/client-portal-setup", icon: Globe },
      { label: "Settings", href: "/settings", icon: Settings },
    ],
  },
];

interface SidebarProps {
  /** Mobile: whether the sidebar overlay is open. Ignored on desktop. */
  mobileOpen?: boolean;
  /** Mobile: close the sidebar overlay. */
  onMobileClose?: () => void;
}

export function Sidebar({ mobileOpen, onMobileClose }: SidebarProps) {
  const pathname = usePathname();
  const sidebarSearchParams = useSearchParams();
  const { brand } = useBrand();

  // Compute which sidebar item should be highlighted based on the
  // current URL. Only ONE item can be active at a time — the one
  // whose href most specifically matches the current pathname + query
  // params. Items with more matching query params beat items with fewer.
  // Prevents multiple LLMO items from highlighting when they share a
  // pathname but differ in query params.
  const activeHref = React.useMemo(() => {
    let best: { href: string; score: number } | null = null;
    for (const section of navSections) {
      for (const item of section.items) {
        const itemPath = item.href.split("?")[0];
        if (itemPath !== pathname) continue;

        const itemQuery = item.href.includes("?") ? item.href.split("?")[1] : "";
        const itemParams = new URLSearchParams(itemQuery);
        const itemParamList = [...itemParams.entries()];

        // All params in href must be present (with matching values) in URL
        const allMatch = itemParamList.every(([k, v]) => sidebarSearchParams.get(k) === v);
        if (!allMatch) continue;

        // Score = number of query params the href specifies. A href with
        // ?tab=ai&view=recommendations beats a href with just ?tab=ai when
        // the URL has both params. Items with no query params score 0 and
        // only win when no other item has matching query params.
        const score = itemParamList.length;
        if (!best || score > best.score) {
          best = { href: item.href, score };
        }
      }
    }
    return best?.href ?? null;
  }, [pathname, sidebarSearchParams]);
  const { state: planState, openUpgrade } = usePlanContext();
  // Superadmin bypass — platform owners never see lock icons or the
  // intercept-and-open-upgrade-modal click handler. Mirrors the same
  // metadata read the middleware admin gate uses.
  const { user: clerkUser } = useUser();
  const isSuperadmin = (() => {
    const meta = (clerkUser?.publicMetadata ?? {}) as Record<string, unknown>;
    return meta.role === "superadmin" || meta.isSuperadmin === true;
  })();

  // Live signals count for the Signals Center nav item's bell badge.
  // Fetched on brand change + refreshed every 60s so a user who
  // dismisses a signal on the Signals Center page sees the bell
  // count update on their next sidebar hover / nav. The signals
  // endpoint is read-only so polling is cheap. Fire-and-forget —
  // a failed fetch leaves the previous count in place rather than
  // flickering to 0.
  const [signalsCount, setSignalsCount] = React.useState<number>(0);
  React.useEffect(() => {
    if (!brand.id) { setSignalsCount(0); return; }
    let cancelled = false;
    const load = async () => {
      try {
        const res = await fetch(`/api/signals?brandId=${brand.id}`, { cache: "no-store" });
        if (!res.ok) return;
        const data = await res.json();
        if (cancelled || !Array.isArray(data)) return;
        // Count only "new" signals — "viewed" and "actioned" are
        // user-acknowledged and shouldn't light up the bell. If the
        // status field is missing (older signals), treat as "new"
        // so the indicator doesn't silently zero out for legacy
        // rows.
        const newCount = data.filter((s: { status?: string }) => (s.status ?? "new") === "new").length;
        setSignalsCount(newCount);
      } catch { /* leave previous count in place */ }
    };
    load();
    const timer = setInterval(load, 60_000);
    return () => { cancelled = true; clearInterval(timer); };
  }, [brand.id]);

  const sidebarContent = (
    <>
      {/* Logo + mobile close */}
      <div className="h-14 flex items-center justify-between px-5 border-b border-white/[0.06]">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src="/images/meseo-logo-white.png" alt="meSEO" className="h-8 w-auto" />
        <span className="text-[9px] font-bold tracking-wider uppercase px-1.5 py-0.5 rounded bg-gradient-to-r from-red-500 to-orange-500 text-white ml-1">
          Early Access
        </span>
        {onMobileClose && (
          <button onClick={onMobileClose} className="md:hidden p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-white/10">
            <X className="w-4 h-4" />
          </button>
        )}
      </div>

      {/* Brand pill */}
      <div className="px-3 pt-3 pb-1">
        <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-white/[0.04] border border-white/[0.06]">
          <div className={`w-6 h-6 rounded ${brand.color} flex items-center justify-center shrink-0`}>
            <span className="text-[8px] font-bold text-white">{brand.initials}</span>
          </div>
          <span className="text-xs font-medium text-slate-300 truncate">{brand.name}</span>
        </div>
      </div>

      <SidebarTaskIndicator />

      <nav className="flex-1 py-2 px-3 overflow-y-auto">
        {navSections.map((section, si) => (
          <div key={section.heading} className={si > 0 ? "mt-4" : ""}>
            <p className="px-3 mb-1.5 text-[9px] font-bold uppercase tracking-[0.15em] text-slate-500">
              {section.heading}
            </p>
            <div className="space-y-px">
              {section.items.map(({ label, href, icon: Icon, badge }) => {
                const hrefPath = href.split("?")[0];
                const isActive = href === activeHref;
                const isSignalsItem = href === "/signals";
                const signalsBadge = isSignalsItem && signalsCount > 0
                  ? (signalsCount > 99 ? "99+" : String(signalsCount))
                  : null;

                // Feature gate check for this sidebar item. A route
                // is "locked" when it's in PROTECTED_ROUTES AND the
                // brand's plan doesn't include that feature. While
                // the plan is still loading we treat items as
                // unlocked so the sidebar doesn't flash lock icons
                // on every page load.
                const featureKey = PROTECTED_ROUTES[href] ?? PROTECTED_ROUTES[hrefPath];
                const isLocked = !isSuperadmin && featureKey && planState
                  ? !planHasFeature(
                      {
                        plan: planState.plan,
                        planExpiresAt: planState.planExpiresAt ? new Date(planState.planExpiresAt) : null,
                      },
                      featureKey,
                    )
                  : false;

                // Click behaviour for locked items: open the upgrade
                // modal instead of navigating to a page that will
                // render the blurred FeatureGate overlay. Cheaper for
                // the user AND avoids loading real feature assets we
                // won't show anyway.
                const onClick = isLocked
                  ? (e: React.MouseEvent) => {
                      e.preventDefault();
                      onMobileClose?.();
                      openUpgrade({ kind: "feature", feature: featureKey! });
                    }
                  : onMobileClose;

                return (
                  <Link
                    key={href}
                    href={href}
                    onClick={onClick}
                    className={cn(
                      "flex items-center gap-2.5 px-3 py-[7px] rounded-md text-[13px] font-medium transition-all duration-150",
                      isActive
                        ? "bg-white/[0.08] text-white border-l-2 border-brand-500 pl-[10px]"
                        : isLocked
                          ? "text-slate-500 hover:text-slate-300 hover:bg-white/[0.04]"
                          : "text-slate-400 hover:text-slate-200 hover:bg-white/[0.04]",
                    )}
                    title={isLocked ? `Upgrade to unlock ${label}` : undefined}
                  >
                    <Icon className="w-[15px] h-[15px] shrink-0" />
                    <span className={cn("flex-1 truncate", isLocked && "opacity-75")}>{label}</span>
                    {isLocked ? (
                      <Lock className="w-3 h-3 text-slate-500 shrink-0" />
                    ) : signalsBadge ? (
                      <span className="text-[9px] font-bold text-white bg-red-500 rounded-full px-1.5 py-0.5 min-w-[18px] text-center tabular-nums">
                        {signalsBadge}
                      </span>
                    ) : badge ? (
                      <span className="text-[8px] font-bold uppercase tracking-wider text-slate-500 bg-white/[0.06] rounded-full px-1.5 py-0.5">
                        {badge}
                      </span>
                    ) : null}
                  </Link>
                );
              })}
            </div>
          </div>
        ))}
      </nav>

      {/* Upgrade CTA */}
      <div className="px-3 pb-4 pt-2 border-t border-white/[0.06]">
        <Link
          href="/pricing"
          onClick={onMobileClose}
          className="flex items-center justify-center gap-2 w-full px-4 py-2.5 rounded-xl bg-gradient-to-r from-brand-600 to-violet-600 text-white text-xs font-bold hover:from-brand-500 hover:to-violet-500 transition-all shadow-lg shadow-brand-900/30"
        >
          <CreditCard className="w-3.5 h-3.5" />
          Upgrade Plan
        </Link>
      </div>
    </>
  );

  return (
    <>
      {/* Desktop sidebar — always visible, hidden on mobile */}
      <aside className="hidden md:flex w-60 shrink-0 bg-slate-950 flex-col h-screen">
        {sidebarContent}
      </aside>

      {/* Mobile sidebar — overlay, slides in from left */}
      {mobileOpen && (
        <>
          <div className="fixed inset-0 bg-black/50 z-40 md:hidden" onClick={onMobileClose} />
          <aside className="fixed inset-y-0 left-0 w-72 bg-slate-950 flex flex-col z-50 md:hidden animate-in slide-in-from-left duration-200">
            {sidebarContent}
          </aside>
        </>
      )}
    </>
  );
}
