import { Link, usePage } from '@inertiajs/react';
import { useState } from 'react';
import {
    AlertTriangle,
    ArrowDownToLine,
    ArrowUpFromLine,
    Bell,
    BookOpen,
    Building,
    Building2,
    CalendarCheck,
    DatabaseBackup,
    Coins,
    FileBarChart,
    FileCheck2,
    Gauge,
    HandCoins,
    History,
    Inbox,
    KeyRound,
    LayoutGrid,
    Package,
    Landmark,
    Layers,
    LifeBuoy,
    PiggyBank,
    Receipt,
    Search,
    Scale,
    Send,
    Sprout,
    Settings2,
    Shapes,
    Tags,
    ShieldCheck,
    ShieldEllipsis,
    UserCheck,
    UserCog,
    UserRound,
    IdCard,
    Users,
    UsersRound,
    Wallet,
} from 'lucide-react';
import AppLogo from '@/components/app-logo';
import { NavMain } from '@/components/nav-main';
import { NavUser } from '@/components/nav-user';
import {
    Sidebar,
    SidebarContent,
    SidebarFooter,
    SidebarHeader,
    SidebarInput,
    SidebarMenu,
    SidebarMenuButton,
    SidebarMenuItem,
} from '@/components/ui/sidebar';
import { dashboard } from '@/routes';
import {
    dashboard as adminDashboard,
    auditTrail as adminAuditTrail,
    securityLog as adminSecurityLog,
} from '@/routes/admin';
import { index as adminBackupsIndex } from '@/routes/admin/backups';
import { index as adminBusinessesIndex } from '@/routes/admin/businesses';
import { edit as adminSettingsEdit } from '@/routes/admin/settings';
import { trialBalance as adminTrialBalance } from '@/routes/admin/accounting';
import { index as adminBranchesIndex } from '@/routes/admin/branches';
import { index as adminLoanProductsIndex } from '@/routes/admin/loan-products';
import { index as adminContributionsIndex } from '@/routes/admin/contributions';
import { index as adminSavingsPlanTypesIndex } from '@/routes/admin/savings-plan-types';
import { index as adminDepositsIndex } from '@/routes/admin/deposits';
import { index as adminFinancingIndex } from '@/routes/admin/financing';
import { index as adminGroupsIndex } from '@/routes/admin/groups';
import { index as adminKycIndex } from '@/routes/admin/kyc';
import { index as adminPermissionsIndex } from '@/routes/admin/permissions';
import { index as adminReportsIndex } from '@/routes/admin/reports';
import { index as adminRolesIndex } from '@/routes/admin/roles';
import { index as adminSupportIndex } from '@/routes/admin/support';
import { index as adminTransactionsIndex } from '@/routes/admin/transactions';
import { index as adminStaffIndex } from '@/routes/admin/staff';
import { index as adminUsersIndex } from '@/routes/admin/users';
import { index as adminWithdrawalsIndex } from '@/routes/admin/withdrawals';
import { index as financingIndex } from '@/routes/financing';
import { index as investmentsIndex } from '@/routes/investments';
import { index as adminInvestmentsIndex } from '@/routes/admin/investments';
import { groups as groupLoans, index as loansIndex } from '@/routes/loans';
import { index as adminFinancingTypesIndex } from '@/routes/admin/financing-types';
import { index as adminLoanCategoriesIndex } from '@/routes/admin/loan-categories';
import { index as adminGuarantorsIndex } from '@/routes/admin/guarantors';
import { index as adminExpensesIndex } from '@/routes/admin/expenses';
import { index as adminIncomeIndex } from '@/routes/admin/income';
import {
    delinquency as adminLoanDelinquency,
    groups as adminGroupLoans,
    index as adminLoansIndex,
} from '@/routes/admin/loans';
import { show as kycShow } from '@/routes/kyc';
import { index as notificationsIndex } from '@/routes/notifications';
import { edit as editProfile } from '@/routes/profile';
import { index as savingsIndex } from '@/routes/savings';
import { index as supportIndex } from '@/routes/support';
import { index as transactionsIndex } from '@/routes/transactions';
import { create as transfersCreate } from '@/routes/transfers';
import { index as withdrawalsIndex } from '@/routes/withdrawals';
import { show as walletShow } from '@/routes/wallet';
import type { NavItem } from '@/types';

export function AppSidebar() {
    const { unreadNotifications, auth } = usePage().props;
    const [query, setQuery] = useState('');

    const overviewItems: NavItem[] = [
        { title: 'Dashboard', href: dashboard(), icon: LayoutGrid },
    ];

    const financeItems: NavItem[] = [
        { title: 'Savings', href: savingsIndex(), icon: PiggyBank },
        {
            title: 'Loans',
            href: loansIndex(),
            icon: Landmark,
            excludes: [groupLoans()],
        },
        { title: 'Group loans', href: groupLoans(), icon: UsersRound },
        { title: 'Financing', href: financingIndex(), icon: HandCoins },
        { title: 'Investments', href: investmentsIndex(), icon: Sprout },
    ];

    const accountItems: NavItem[] = [
        { title: 'Wallet', href: walletShow(), icon: Wallet },
        { title: 'Transfer', href: transfersCreate(), icon: Send },
        { title: 'Withdraw', href: withdrawalsIndex(), icon: ArrowUpFromLine },
        { title: 'Transactions', href: transactionsIndex(), icon: History },
    ];

    const helpItems: NavItem[] = [
        {
            title: 'Notifications',
            href: notificationsIndex(),
            icon: Bell,
            badge: unreadNotifications,
        },
        { title: 'Support', href: supportIndex(), icon: LifeBuoy },
        { title: 'Verification', href: kycShow(), icon: ShieldCheck },
        { title: 'Profile', href: editProfile(), icon: UserRound },
    ];

    const can = (permission: string) => auth.permissions.includes(permission);

    const when = (allowed: boolean, items: NavItem[]): NavItem[] =>
        allowed ? items : [];

    /**
     * Staff menu, grouped as in the AMCSMS portal structure (§27). Each
     * section shows only the pages the signed-in staff member may open.
     */
    const adminSections: { label: string; items: NavItem[] }[] = [
        {
            label: 'Operations',
            items: [
                ...when(auth.permissions.length > 0, [
                    {
                        title: 'Admin dashboard',
                        href: adminDashboard(),
                        icon: Gauge,
                        exact: true,
                    },
                ]),
                ...when(can('members.view'), [
                    {
                        title: 'Members',
                        href: adminUsersIndex(),
                        icon: Users,
                    },
                    {
                        title: 'Staff',
                        href: adminStaffIndex(),
                        icon: IdCard,
                    },
                ]),
                ...when(can('kyc.review'), [
                    {
                        title: 'KYC review',
                        href: adminKycIndex(),
                        icon: FileCheck2,
                    },
                ]),
                ...when(can('savings.view'), [
                    {
                        title: 'Smart Save Group',
                        href: adminGroupsIndex(),
                        icon: UsersRound,
                    },
                ]),
                ...when(can('reports.view'), [
                    {
                        title: 'Branches',
                        href: adminBranchesIndex(),
                        icon: Building2,
                    },
                ]),
                ...when(can('savings.record'), [
                    {
                        title: 'Deposits',
                        href: adminDepositsIndex(),
                        icon: ArrowDownToLine,
                    },
                ]),
                ...when(can('savings.view'), [
                    {
                        title: 'Contributions',
                        href: adminContributionsIndex(),
                        icon: CalendarCheck,
                    },
                ]),
                ...when(can('withdrawals.view'), [
                    {
                        title: 'Withdrawals',
                        href: adminWithdrawalsIndex(),
                        icon: ArrowUpFromLine,
                    },
                ]),
                ...when(can('investments.manage'), [
                    {
                        title: 'Investments',
                        href: adminInvestmentsIndex(),
                        icon: Sprout,
                    },
                ]),
                ...when(can('support.manage'), [
                    {
                        title: 'Support inbox',
                        href: adminSupportIndex(),
                        icon: Inbox,
                    },
                ]),
            ],
        },
        {
            label: 'Loans',
            items: when(can('loans.view'), [
                {
                    title: 'Applications',
                    href: adminLoansIndex(),
                    icon: Landmark,
                    excludes: [adminGroupLoans(), adminLoanDelinquency()],
                },
                {
                    title: 'Group loans',
                    href: adminGroupLoans(),
                    icon: UsersRound,
                },
                {
                    title: 'Loan products',
                    href: adminLoanProductsIndex(),
                    icon: Package,
                },
                {
                    title: 'Guarantors',
                    href: adminGuarantorsIndex(),
                    icon: UserCheck,
                },
                {
                    title: 'Delinquency',
                    href: adminLoanDelinquency(),
                    icon: AlertTriangle,
                },
                {
                    title: 'Financing review',
                    href: adminFinancingIndex(),
                    icon: HandCoins,
                },
            ]),
        },
        {
            label: 'Types & categories',
            items: [
                ...when(can('loans.products'), [
                    {
                        title: 'Loan categories',
                        href: adminLoanCategoriesIndex(),
                        icon: Tags,
                    },
                    {
                        title: 'Financing types',
                        href: adminFinancingTypesIndex(),
                        icon: Shapes,
                    },
                ]),
                ...when(can('contributions.manage'), [
                    {
                        title: 'Savings plan types',
                        href: adminSavingsPlanTypesIndex(),
                        icon: Layers,
                    },
                ]),
            ],
        },
        {
            label: 'Finance',
            items: [
                ...when(can('accounting.view'), [
                    { title: 'Income', href: adminIncomeIndex(), icon: Coins },
                    {
                        title: 'Expenses',
                        href: adminExpensesIndex(),
                        icon: Receipt,
                    },
                    {
                        title: 'Ledger',
                        href: adminTransactionsIndex(),
                        icon: BookOpen,
                    },
                    {
                        title: 'Financial statements',
                        href: adminTrialBalance(),
                        icon: Scale,
                    },
                ]),
                ...when(auth.permissions.length > 0, [
                    {
                        title: 'Reports',
                        href: adminReportsIndex(),
                        icon: FileBarChart,
                    },
                ]),
            ],
        },
        {
            label: 'Administration',
            items: [
                ...when(can('audit.view'), [
                    {
                        title: 'Audit trail',
                        href: adminAuditTrail(),
                        icon: History,
                    },
                    {
                        title: 'Security log',
                        href: adminSecurityLog(),
                        icon: ShieldEllipsis,
                    },
                ]),
                ...when(auth.isSuperAdmin, [
                    {
                        title: 'Businesses',
                        href: adminBusinessesIndex(),
                        icon: Building,
                    },
                ]),
                ...when(auth.isSuperAdmin, [
                    { title: 'Roles', href: adminRolesIndex(), icon: UserCog },
                    {
                        title: 'Permissions',
                        href: adminPermissionsIndex(),
                        icon: KeyRound,
                    },
                ]),
                ...when(auth.isSuperAdmin, [
                    {
                        title: 'Backups',
                        href: adminBackupsIndex(),
                        icon: DatabaseBackup,
                    },
                ]),
                ...when(can('settings.manage'), [
                    {
                        title: 'System settings',
                        href: adminSettingsEdit(),
                        icon: Settings2,
                    },
                ]),
            ],
        },
    ].filter((section) => section.items.length > 0);

    const isStaff = adminSections.length > 0;

    const search = query.trim().toLowerCase();
    const sections = [
        ...adminSections,
        { label: isStaff ? 'My account' : undefined, items: overviewItems },
        { label: 'Finance', items: financeItems },
        { label: 'Account', items: accountItems },
        { label: 'Help & settings', items: helpItems },
    ]
        .map((section) => ({
            ...section,
            items: search
                ? section.items.filter((item) =>
                      `${item.title} ${section.label ?? ''}`
                          .toLowerCase()
                          .includes(search),
                  )
                : section.items,
        }))
        .filter((section) => section.items.length > 0);

    return (
        <Sidebar collapsible="icon" variant="inset">
            <SidebarHeader className="mx-3 h-16 shrink-0 justify-center border-b border-sidebar-border px-0 py-0 transition-[height] ease-linear group-data-[collapsible=icon]:h-12">
                <SidebarMenu>
                    <SidebarMenuItem>
                        <SidebarMenuButton
                            size="lg"
                            asChild
                            className="hover:bg-transparent active:bg-transparent"
                        >
                            <Link href={dashboard()} prefetch>
                                <AppLogo />
                            </Link>
                        </SidebarMenuButton>
                    </SidebarMenuItem>
                </SidebarMenu>
            </SidebarHeader>

            <div className="relative mx-3 mt-3 group-data-[collapsible=icon]:hidden">
                <Search
                    aria-hidden="true"
                    className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-white/40"
                />
                <SidebarInput
                    type="search"
                    value={query}
                    onChange={(event) => setQuery(event.target.value)}
                    onKeyDown={(event) => {
                        if (event.key === 'Escape') {
                            setQuery('');
                        }
                    }}
                    placeholder="Search menu"
                    aria-label="Search menu"
                    className="h-9 rounded-lg border-white/10 bg-white/5 pl-9 text-[14px] text-white placeholder:text-white/40 focus-visible:border-highlight/50 focus-visible:ring-highlight/20"
                />
            </div>

            <SidebarContent className="gap-1 py-2">
                {sections.map((section, index) => (
                    <NavMain
                        key={`${section.label ?? 'overview'}-${index}`}
                        items={section.items}
                        label={section.label}
                    />
                ))}
                {sections.length === 0 && (
                    <p className="px-6 py-4 text-sm text-white/50">
                        No menu items match “{query.trim()}”.
                    </p>
                )}
            </SidebarContent>

            <SidebarFooter className="mx-3 border-t border-sidebar-border px-0 py-3">
                <NavUser />
            </SidebarFooter>
        </Sidebar>
    );
}
