import {
  LayoutDashboard,
  Settings,
  UserCog,
  CreditCard,
  // People (Members + Access)
  UserCheck,
  UserPlus,
  IdCard,
  ClipboardList,
  // Courses
  GraduationCap,
  CalendarDays,
  MapPin,
  UserRound,
  // Events
  CalendarHeart,
  Ticket,
  PartyPopper,
  // Bookings
  Hotel,
  BedDouble,
  Contact,
  CalendarRange,
  // Finance
  Wallet,
  Receipt,
  Landmark,
  BarChart3,
  // Documents
  FileText,
  FilePlus,
  FileStack,
  FolderOpen,
  // Newsletter
  Mail,
  MailPlus,
  FileCode,
  // Site Builder
  PanelTop,
  Newspaper,
  Palette,
  // Modules
  Database,
} from 'lucide-react';

import { NavigationConfigSchema } from '@kit/ui/navigation-schema';

import featureFlagsConfig from '~/config/feature-flags.config';
import pathsConfig from '~/config/paths.config';

const iconClasses = 'w-4';

const getRoutes = (account: string) => {
  const routes: Array<
    | {
        label: string;
        collapsible?: boolean;
        collapsed?: boolean;
        children: Array<
          | {
              label: string;
              path: string;
              Icon: React.ReactNode;
              highlightMatch?: string;
            }
          | undefined
        >;
      }
    | { divider: true }
  > = [
    // ── Dashboard ──
    {
      label: 'common:routes.dashboard',
      children: [
        {
          label: 'common:routes.dashboard',
          path: pathsConfig.app.accountHome.replace('[account]', account),
          Icon: <LayoutDashboard className={iconClasses} />,
          highlightMatch: `${pathsConfig.app.home}$`,
        },
      ],
    },
  ];

  // ── People (Members + Access) ──
  {
    const peopleChildren: Array<{
      label: string;
      path: string;
      Icon: React.ReactNode;
    }> = [];

    if (featureFlagsConfig.enableMemberManagement) {
      peopleChildren.push(
        {
          label: 'common:routes.clubMembers',
          path: createPath(pathsConfig.app.accountCmsMembers, account),
          Icon: <UserCheck className={iconClasses} />,
        },
        {
          label: 'common:routes.memberApplications',
          path: createPath(
            pathsConfig.app.accountCmsMembers + '/applications',
            account,
          ),
          Icon: <UserPlus className={iconClasses} />,
        },
        // NOTE: memberPortal page does not exist yet — nav entry commented out until built
        // {
        //   label: 'common:routes.memberPortal',
        //   path: createPath(
        //     pathsConfig.app.accountCmsMembers + '/portal',
        //     account,
        //   ),
        //   Icon: <KeyRound className={iconClasses} />,
        // },
        {
          label: 'common:routes.memberCards',
          path: createPath(
            pathsConfig.app.accountCmsMembers + '/cards',
            account,
          ),
          Icon: <IdCard className={iconClasses} />,
        },
        {
          label: 'common:routes.memberDues',
          path: createPath(
            pathsConfig.app.accountCmsMembers + '/dues',
            account,
          ),
          Icon: <ClipboardList className={iconClasses} />,
        },
      );
    }

    // Admin users who can log in — always visible
    peopleChildren.push({
      label: 'common:routes.accessAndRoles',
      path: createPath(pathsConfig.app.accountMembers, account),
      Icon: <UserCog className={iconClasses} />,
    });

    routes.push({
      label: 'common:routes.people',
      collapsible: true,
      children: peopleChildren,
    });
  }

  // ── Courses ──
  if (featureFlagsConfig.enableCourseManagement) {
    routes.push({
      label: 'common:routes.courseManagement',
      collapsible: true,
      children: [
        {
          label: 'common:routes.courseList',
          path: createPath(pathsConfig.app.accountCourses, account),
          Icon: <GraduationCap className={iconClasses} />,
        },
        {
          label: 'common:routes.courseCalendar',
          path: createPath(
            pathsConfig.app.accountCourses + '/calendar',
            account,
          ),
          Icon: <CalendarDays className={iconClasses} />,
        },
        {
          label: 'common:routes.courseInstructors',
          path: createPath(
            pathsConfig.app.accountCourses + '/instructors',
            account,
          ),
          Icon: <UserRound className={iconClasses} />,
        },
        {
          label: 'common:routes.courseLocations',
          path: createPath(
            pathsConfig.app.accountCourses + '/locations',
            account,
          ),
          Icon: <MapPin className={iconClasses} />,
        },
      ],
    });
  }

  // ── Events ──
  routes.push({
    label: 'common:routes.eventManagement',
    collapsible: true,
    children: [
      {
        label: 'common:routes.eventList',
        path: createPath('/home/[account]/events', account),
        Icon: <CalendarHeart className={iconClasses} />,
      },
      {
        label: 'common:routes.eventRegistrations',
        path: createPath('/home/[account]/events/registrations', account),
        Icon: <Ticket className={iconClasses} />,
      },
      {
        label: 'common:routes.holidayPasses',
        path: createPath('/home/[account]/events/holiday-passes', account),
        Icon: <PartyPopper className={iconClasses} />,
      },
    ],
  });

  // ── Bookings ──
  if (featureFlagsConfig.enableBookingManagement) {
    routes.push({
      label: 'common:routes.bookingManagement',
      collapsible: true,
      children: [
        {
          label: 'common:routes.bookingList',
          path: createPath(pathsConfig.app.accountBookings, account),
          Icon: <Hotel className={iconClasses} />,
        },
        {
          label: 'common:routes.bookingCalendar',
          path: createPath(
            pathsConfig.app.accountBookings + '/calendar',
            account,
          ),
          Icon: <CalendarRange className={iconClasses} />,
        },
        {
          label: 'common:routes.bookingRooms',
          path: createPath(pathsConfig.app.accountBookings + '/rooms', account),
          Icon: <BedDouble className={iconClasses} />,
        },
        {
          label: 'common:routes.bookingGuests',
          path: createPath(
            pathsConfig.app.accountBookings + '/guests',
            account,
          ),
          Icon: <Contact className={iconClasses} />,
        },
      ],
    });
  }

  // ── Finance ──
  if (featureFlagsConfig.enableSepaPayments) {
    routes.push({
      label: 'common:routes.financeManagement',
      collapsible: true,
      children: [
        {
          label: 'common:routes.financeOverview',
          path: createPath(pathsConfig.app.accountFinance, account),
          Icon: <Wallet className={iconClasses} />,
        },
        {
          label: 'common:routes.financeInvoices',
          path: createPath(
            pathsConfig.app.accountFinance + '/invoices',
            account,
          ),
          Icon: <Receipt className={iconClasses} />,
        },
        {
          label: 'common:routes.financeSepa',
          path: createPath(pathsConfig.app.accountFinance + '/sepa', account),
          Icon: <Landmark className={iconClasses} />,
        },
        {
          label: 'common:routes.financePayments',
          path: createPath(
            pathsConfig.app.accountFinance + '/payments',
            account,
          ),
          Icon: <BarChart3 className={iconClasses} />,
        },
      ],
    });
  }

  // ── Documents ──
  if (featureFlagsConfig.enableDocumentGeneration) {
    routes.push({
      label: 'common:routes.documentManagement',
      collapsible: true,
      children: [
        {
          label: 'common:routes.documentOverview',
          path: createPath(pathsConfig.app.accountDocuments, account),
          Icon: <FileText className={iconClasses} />,
        },
        {
          label: 'common:routes.documentGenerate',
          path: createPath(
            pathsConfig.app.accountDocuments + '/generate',
            account,
          ),
          Icon: <FilePlus className={iconClasses} />,
        },
        {
          label: 'common:routes.documentTemplates',
          path: createPath(
            pathsConfig.app.accountDocuments + '/templates',
            account,
          ),
          Icon: <FileStack className={iconClasses} />,
        },
        {
          label: 'common:routes.files',
          path: createPath(pathsConfig.app.accountFiles, account),
          Icon: <FolderOpen className={iconClasses} />,
        },
      ],
    });
  }

  // ── Newsletter ──
  if (featureFlagsConfig.enableNewsletter) {
    routes.push({
      label: 'common:routes.newsletterManagement',
      collapsible: true,
      children: [
        {
          label: 'common:routes.newsletterCampaigns',
          path: createPath(pathsConfig.app.accountNewsletter, account),
          Icon: <Mail className={iconClasses} />,
        },
        {
          label: 'common:routes.newsletterNew',
          path: createPath(pathsConfig.app.accountNewsletter + '/new', account),
          Icon: <MailPlus className={iconClasses} />,
        },
        {
          label: 'common:routes.newsletterTemplates',
          path: createPath(
            pathsConfig.app.accountNewsletter + '/templates',
            account,
          ),
          Icon: <FileCode className={iconClasses} />,
        },
      ],
    });
  }

  // ── Site Builder ──
  if (featureFlagsConfig.enableSiteBuilder) {
    routes.push({
      label: 'common:routes.siteBuilder',
      collapsible: true,
      children: [
        {
          label: 'common:routes.sitePages',
          path: createPath(pathsConfig.app.accountSiteBuilder, account),
          Icon: <PanelTop className={iconClasses} />,
        },
        {
          label: 'common:routes.sitePosts',
          path: createPath(
            pathsConfig.app.accountSiteBuilder + '/posts',
            account,
          ),
          Icon: <Newspaper className={iconClasses} />,
        },
        {
          label: 'common:routes.siteSettings',
          path: createPath(
            pathsConfig.app.accountSiteBuilder + '/settings',
            account,
          ),
          Icon: <Palette className={iconClasses} />,
        },
      ],
    });
  }

  // Note: Fischerei, Meetings, and Verband sections are injected at runtime
  // via injectAccountFeatureRoutes() in the layout, based on per-account
  // settings (account_settings.features). They are NOT added here to avoid
  // duplicate entries when both the global feature flag and per-account
  // setting are enabled.

  // ── Administration ──
  {
    const adminChildren: Array<
      | {
          label: string;
          path: string;
          Icon: React.ReactNode;
        }
      | undefined
    > = [
      {
        label: 'common:routes.accountSettings',
        path: createPath(pathsConfig.app.accountSettings, account),
        Icon: <Settings className={iconClasses} />,
      },
    ];

    if (featureFlagsConfig.enableModuleBuilder) {
      adminChildren.push({
        label: 'common:routes.moduleList',
        path: createPath(pathsConfig.app.accountModules, account),
        Icon: <Database className={iconClasses} />,
      });
    }

    if (featureFlagsConfig.enableTeamAccountBilling) {
      adminChildren.push({
        label: 'common:routes.billing',
        path: createPath(pathsConfig.app.accountBilling, account),
        Icon: <CreditCard className={iconClasses} />,
      });
    }

    routes.push({
      label: 'common:routes.administration',
      collapsible: false,
      children: adminChildren,
    });
  }

  return routes;
};

export function getTeamAccountSidebarConfig(account: string) {
  return NavigationConfigSchema.parse({
    routes: getRoutes(account),
    style: process.env.NEXT_PUBLIC_TEAM_NAVIGATION_STYLE,
    sidebarCollapsed: process.env.NEXT_PUBLIC_TEAM_SIDEBAR_COLLAPSED,
    sidebarCollapsedStyle: process.env.NEXT_PUBLIC_SIDEBAR_COLLAPSIBLE_STYLE,
  });
}

function createPath(path: string, account: string) {
  return path.replace('[account]', account);
}
