import {
  AlertTriangle,
  BarChart2,
  BarChart3,
  Bell,
  BookOpen,
  Bot,
  CalendarDays,
  Clock,
  CreditCard,
  FileCode,
  FileSearch,
  FileText,
  GitMerge,
  Globe,
  HardDrive,
  Heart,
  History,
  Key,
  Layers,
  LayoutDashboard,
  Lightbulb,
  LineChart,
  Link,
  Mail,
  MailX,
  MessageSquare,
  Monitor,
  Network,
  Package,
  Palette,
  Plug,
  Quote,
  Radio,
  ScrollText,
  Search,
  Server,
  Settings,
  ShieldCheck,
  Sliders,
  Stethoscope,
  ThumbsUp,
  ToggleLeft,
  TrendingDown,
  TrendingUp,
  Upload,
  Users,
  Users2,
  Wifi,
  Workflow,
  Zap,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';

import type { Features } from '@/types';

export interface AdminNavItem {
  href: string;
  label: string;
  icon: LucideIcon;
  featureFlag?: keyof Features;
  /** Hide this item when the current user's admin role is below this minimum. */
  minimumRole?: 'viewer' | 'operator' | 'admin' | 'super_admin';
}

export interface AdminNavGroup {
  label: string;
  items: AdminNavItem[];
}

const ROLE_LEVELS: Record<string, number> = {
  viewer: 0,
  operator: 1,
  admin: 2,
  super_admin: 3,
};

function roleLevel(role: string | null | undefined): number {
  return ROLE_LEVELS[role ?? ''] ?? 0;
}

export const adminNavigationGroups: AdminNavGroup[] = [
  {
    label: 'Overview',
    items: [
      { href: '/admin', label: 'Metrics', icon: LayoutDashboard },
      { href: '/admin/founder-dashboard', label: 'Founder Dashboard', icon: LineChart },
      { href: '/admin/metrics', label: 'Product Metrics', icon: BarChart3 },
      { href: '/admin/lifecycle', label: 'Lifecycle', icon: Workflow },
      { href: '/admin/impact-reports', label: 'Impact Reports', icon: TrendingUp },
    ],
  },
  {
    label: 'Management',
    items: [
      { href: '/admin/users', label: 'Users', icon: Users, minimumRole: 'operator' },
      { href: '/admin/sites', label: 'Sites', icon: Globe, minimumRole: 'operator' },
      { href: '/admin/audit-logs', label: 'Audit Logs', icon: ScrollText },
      {
        href: '/admin/limit-policies',
        label: 'Limit Policies',
        icon: Sliders,
        minimumRole: 'operator',
      },
      { href: '/admin/feedback-dashboard', label: 'Feedback', icon: MessageSquare },
      { href: '/admin/nps-surveys', label: 'NPS Surveys', icon: Heart },
      { href: '/admin/feature-requests', label: 'Feature Requests', icon: Lightbulb },
      {
        href: '/admin/breach-incidents',
        label: 'Breach Incidents',
        icon: AlertTriangle,
        minimumRole: 'operator',
      },
      { href: '/admin/dsar', label: 'DSAR Requests', icon: FileSearch, minimumRole: 'operator' },
      {
        href: '/admin/email-suppressions',
        label: 'Email Suppressions',
        icon: MailX,
        minimumRole: 'operator',
      },
      {
        href: '/admin/user-brandings',
        label: 'User Brandings',
        icon: Palette,
        minimumRole: 'operator',
      },
    ],
  },
  {
    label: 'Content',
    items: [
      { href: '/admin/blog-posts', label: 'Blog Posts', icon: BookOpen, minimumRole: 'operator' },
      {
        href: '/admin/changelog-entries',
        label: 'Changelog',
        icon: ScrollText,
        minimumRole: 'operator',
      },
      { href: '/admin/subscribers', label: 'Subscribers', icon: Mail, minimumRole: 'operator' },
      { href: '/admin/testimonials', label: 'Testimonials', icon: Quote, minimumRole: 'operator' },
      {
        href: '/admin/webhook-endpoints',
        label: 'Webhook Endpoints',
        icon: Radio,
        featureFlag: 'webhooks',
        minimumRole: 'operator',
      },
      {
        href: '/admin/incoming-webhooks',
        label: 'Incoming Webhooks',
        icon: Radio,
        featureFlag: 'webhooks',
        minimumRole: 'operator',
      },
      { href: '/admin/ai-templates', label: 'AI Templates', icon: Bot, minimumRole: 'operator' },
    ],
  },
  {
    label: 'Features',
    items: [
      {
        href: '/admin/billing',
        label: 'Billing',
        icon: CreditCard,
        featureFlag: 'billing',
        minimumRole: 'operator',
      },
      {
        href: '/admin/webhooks',
        label: 'Webhooks',
        icon: Radio,
        featureFlag: 'webhooks',
        minimumRole: 'operator',
      },
      {
        href: '/admin/webhook-deliveries',
        label: 'Webhook Deliveries',
        icon: Radio,
        featureFlag: 'webhooks',
        minimumRole: 'operator',
      },
      {
        href: '/admin/tokens',
        label: 'API Tokens',
        icon: Key,
        featureFlag: 'apiTokens',
        minimumRole: 'operator',
      },
      {
        href: '/admin/social-auth',
        label: 'Social Auth',
        icon: Users2,
        featureFlag: 'socialAuth',
        minimumRole: 'operator',
      },
      {
        href: '/admin/notifications',
        label: 'Notifications',
        icon: Bell,
        featureFlag: 'notifications',
        minimumRole: 'operator',
      },
      {
        href: '/admin/two-factor',
        label: 'Two-Factor',
        icon: ShieldCheck,
        featureFlag: 'twoFactor',
        minimumRole: 'operator',
      },
    ],
  },
  {
    label: 'Monitoring',
    items: [
      { href: '/admin/operations', label: 'Operations', icon: Monitor },
      { href: '/admin/ai-keys', label: 'AI Key Health', icon: Key },
      { href: '/admin/analysis-runs', label: 'Analysis Runs', icon: Layers },
      { href: '/admin/ai-jobs', label: 'AI Jobs', icon: Bot },
      { href: '/admin/batch-jobs', label: 'Batch Jobs', icon: Package },
      { href: '/admin/traffic-alerts', label: 'Traffic Alerts', icon: AlertTriangle },
      { href: '/admin/data-health', label: 'Data Health', icon: Stethoscope },
      { href: '/admin/gsc-metrics', label: 'GSC Metrics', icon: BarChart2 },
      { href: '/admin/gsc-connections', label: 'GSC Connections', icon: Wifi },
      { href: '/admin/wp-connections', label: 'WP Connections', icon: Plug },
    ],
  },
  {
    label: 'Analysis Data',
    items: [
      { href: '/admin/findings', label: 'Findings', icon: Search },
      { href: '/admin/recommendations', label: 'Recommendations', icon: Lightbulb },
      { href: '/admin/cannibalization-runs', label: 'Cannibalization Runs', icon: GitMerge },
      { href: '/admin/topic-cluster-runs', label: 'Topic Cluster Runs', icon: Network },
      { href: '/admin/topic-clusters', label: 'Topic Clusters', icon: Network },
      { href: '/admin/page-decay-runs', label: 'Page Decay Runs', icon: TrendingDown },
      { href: '/admin/freshness-recommendations', label: 'Freshness Recs', icon: TrendingDown },
      { href: '/admin/recommendation-roi-snapshots', label: 'ROI Snapshots', icon: TrendingUp },
      { href: '/admin/opportunity-feedback', label: 'Opportunity Feedback', icon: ThumbsUp },
    ],
  },
  {
    label: 'Content Data',
    items: [
      { href: '/admin/wp-posts', label: 'WP Posts', icon: FileCode },
      { href: '/admin/wp-publish-logs', label: 'WP Publish Logs', icon: Upload },
      { href: '/admin/ai-drafts', label: 'AI Drafts', icon: Bot },
      { href: '/admin/content-briefs', label: 'Content Briefs', icon: FileText },
      { href: '/admin/content-snapshots', label: 'Content Snapshots', icon: History },
      { href: '/admin/serp-snapshots', label: 'SERP Snapshots', icon: BarChart2 },
      { href: '/admin/keyword-opportunities', label: 'Keyword Opportunities', icon: TrendingUp },
      { href: '/admin/keyword-opportunity-runs', label: 'Keyword Opp. Runs', icon: TrendingUp },
    ],
  },
  {
    label: 'Planning',
    items: [
      { href: '/admin/reports', label: 'Reports', icon: BarChart3, minimumRole: 'operator' },
      {
        href: '/admin/report-templates',
        label: 'Report Templates',
        icon: FileText,
        minimumRole: 'operator',
      },
      {
        href: '/admin/shared-report-links',
        label: 'Shared Report Links',
        icon: Link,
        minimumRole: 'operator',
      },
      {
        href: '/admin/seo-calendar',
        label: 'SEO Calendar',
        icon: CalendarDays,
        minimumRole: 'operator',
      },
      { href: '/admin/site-members', label: 'Site Members', icon: Users2, minimumRole: 'operator' },
    ],
  },
  {
    label: 'System',
    items: [
      {
        href: '/admin/feature-flags',
        label: 'Feature Flags',
        icon: ToggleLeft,
        minimumRole: 'operator',
      },
      { href: '/admin/health', label: 'Health', icon: Heart },
      { href: '/admin/config', label: 'Config', icon: Settings },
      { href: '/admin/system', label: 'System Info', icon: Server },
      { href: '/admin/dlq', label: 'Dead Letter Queue', icon: MailX, minimumRole: 'operator' },
      {
        href: '/admin/circuit-breaker',
        label: 'Circuit Breaker',
        icon: Zap,
        minimumRole: 'operator',
      },
      { href: '/admin/cache', label: 'Cache', icon: HardDrive, minimumRole: 'operator' },
      { href: '/admin/scheduled-tasks', label: 'Scheduled Tasks', icon: Clock },
      { href: '/admin/sessions', label: 'Sessions', icon: Users, minimumRole: 'operator' },
    ],
  },
];

export function getVisibleAdminGroups(
  features: Features,
  adminRole?: string | null,
): AdminNavGroup[] {
  const userLevel = roleLevel(adminRole);

  return adminNavigationGroups
    .map((group) => ({
      ...group,
      items: group.items.filter(
        (item) =>
          (!item.featureFlag || features[item.featureFlag]) &&
          (!item.minimumRole || userLevel >= roleLevel(item.minimumRole)),
      ),
    }))
    .filter((group) => group.items.length > 0);
}
