import { Link, usePage } from "@inertiajs/react";

import {
    BarChart3,
    Building2,
    CalendarDays,
    CreditCard,
    FileText,
    FolderGit2,
    HelpCircle,
    LayoutGrid,
    MapPinned,
    Package,
    Receipt,
    Settings2,
    ShoppingCart,
    Tags,
    Truck,
    UserRound,
    Users,
} from "lucide-react";

import AppLogo from "@/components/app-logo";
import { NavMain } from "@/components/nav-main";

import {
    Sidebar,
    SidebarContent,
    SidebarFooter,
    SidebarHeader,
    SidebarMenu,
    SidebarMenuButton,
    SidebarMenuItem,
} from "@/components/ui/sidebar";

import { dashboard } from "@/routes";
import type { NavItem } from "@/types";

type RoleSlug =
    | "admin"
    | "manager"
    | "supervisor"
    | "admin-pengiriman"
    | "pengiriman"
    | "sales"
    | "platform-owner"
    | string;

/*
|--------------------------------------------------------------------------
| COMMON
|--------------------------------------------------------------------------
*/

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

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

const platformOverviewItems: NavItem[] = [
    {
        title: "Dashboard",
        href: "/platform/dashboard",
        icon: LayoutGrid,
    },
];

/*
|--------------------------------------------------------------------------
| PLATFORM OWNER
|--------------------------------------------------------------------------
*/

const platformCompanyItems: NavItem[] = [
    {
        title: "Perusahaan",
        href: "/platform/companies",
        icon: Building2,
    },
    {
        title: "Paket Langganan",
        href: "/platform/plans",
        icon: Tags,
    },
    {
        title: "Langganan",
        href: "/platform/subscriptions",
        icon: CreditCard,
    },
    {
        title: "Pembayaran",
        href: "/platform/payments",
        icon: Receipt,
    },
];

const platformUserItems: NavItem[] = [
    {
        title: "Pengguna",
        href: "/platform/users",
        icon: Users,
    },
    {
        title: "Role",
        href: "/platform/roles",
        icon: UserRound,
    },
    {
        title: "Permission",
        href: "/platform/permissions",
        icon: Settings2,
    },
];

const platformReportItems: NavItem[] = [
    {
        title: "Statistik Perusahaan",
        href: "/platform/reports/companies",
        icon: BarChart3,
    },
    {
        title: "Penggunaan Sistem",
        href: "/platform/reports/usage",
        icon: BarChart3,
    },
    {
        title: "Pendapatan",
        href: "/platform/reports/revenue",
        icon: CreditCard,
    },
];

/*
|--------------------------------------------------------------------------
| COMPANY - MASTER DATA
|--------------------------------------------------------------------------
*/

const areaItems: NavItem[] = [
    {
        title: "Area",
        href: "/crm/areas",
        icon: MapPinned,
    },
];

const customerItems: NavItem[] = [
    {
        title: "Customer",
        href: "/crm/customers",
        icon: Users,
    },
    {
        title: "Kategori Customer",
        href: "/crm/customer-categories",
        icon: Tags,
    },
    {
        title: "Peta Customer",
        href: "/crm/customer-map",
        icon: MapPinned,
    },
];

const productItems: NavItem[] = [
    {
        title: "Product",
        href: "/crm/products",
        icon: Package,
    },
    {
        title: "Kategori Product",
        href: "/crm/product-categories",
        icon: Tags,
    },
];

const customerViewItems: NavItem[] = [
    {
        title: "Customer",
        href: "/crm/customers",
        icon: Users,
    },
];

const productViewItems: NavItem[] = [
    {
        title: "Product",
        href: "/crm/products",
        icon: Package,
    },
];

const salesItems: NavItem[] = [
    {
        title: "Sales",
        href: "/crm/sales",
        icon: UserRound,
    },
    {
        title: "Teams",
        href: "/crm/teams",
        icon: Users,
    },
    {
        title: "Sales ↔ Area",
        href: "/crm/sales-areas",
        icon: MapPinned,
    },
    {
        title: "Kinerja Sales",
        href: "/crm/sales/performance",
        icon: BarChart3,
    },
];

/*
|--------------------------------------------------------------------------
| COMPANY - TRANSACTION
|--------------------------------------------------------------------------
*/

const commerceItems: NavItem[] = [
    {
        title: "Order",
        href: "/crm/orders",
        icon: ShoppingCart,
    },
];

const financeItems: NavItem[] = [
    {
        title: "Invoice",
        href: "/crm/invoices",
        icon: Receipt,
    },
    {
        title: "Payment",
        href: "/crm/payments",
        icon: CreditCard,
    },
    {
        title: "Outstanding",
        href: "/crm/collection-schedules",
        icon: CreditCard,
    },
];

/*
|--------------------------------------------------------------------------
| COMPANY - VISIT
|--------------------------------------------------------------------------
*/

const visitItems: NavItem[] = [
    {
        title: "Visits",
        href: "/crm/visits",
        icon: MapPinned,
    },
    {
        title: "Jadwal Visit",
        href: "/crm/visit-schedules",
        icon: CalendarDays,
    },
    {
        title: "Visit Per Sales",
        href: "/crm/visits/per-sales",
        icon: MapPinned,
    },
    {
        title: "Visit Per Periode",
        href: "/crm/visits/per-period",
        icon: MapPinned,
    },
    {
        title: "Visit On Map",
        href: "/crm/visits/onmap",
        icon: MapPinned,
    },
];

/*
|--------------------------------------------------------------------------
| COMPANY - DELIVERY
|--------------------------------------------------------------------------
*/

const deliveryItems: NavItem[] = [
    {
        title: "Delivery",
        href: "/crm/deliveries",
        icon: Truck,
    },
];

/*
|--------------------------------------------------------------------------
| COMPANY - REPORT
|--------------------------------------------------------------------------
*/

const reportItems: NavItem[] = [
    {
        title: "Laporan Penjualan",
        href: "/crm/reports",
        icon: FileText,
    },
];

/*
|--------------------------------------------------------------------------
| COMPANY - ADMINISTRATION
|--------------------------------------------------------------------------
*/

const companyAdminItems: NavItem[] = [
    {
        title: "User Management",
        href: "/crm/users",
        icon: Users,
    },
    {
        title: "Role & Permission",
        href: "/crm/roles",
        icon: UserRound,
    },
    {
        title: "Perusahaan",
        href: "/settings/company",
        icon: Building2,
    },
];

/*
|--------------------------------------------------------------------------
| INTEGRATION
|--------------------------------------------------------------------------
*/

const integrationItems: NavItem[] = [
    {
        title: "Activity Log",
        href: "/audit-logs",
        icon: FolderGit2,
    },
];

/*
|--------------------------------------------------------------------------
| PERMISSION HELPER
|--------------------------------------------------------------------------
*/

type SidebarSection = {
    items: NavItem[];
    label: string;
};

const permissionByHref: Record<string, string | string[]> = {
    "/crm/analytics": "reports.view",
    "/crm/customers": "customers.view",
    "/crm/customer-map": "customers.view",
    "/crm/customer-categories": "customer_categories.view",
    "/crm/areas": "areas.manage",
    "/crm/products": "products.view",
    "/crm/product-categories": "product_categories.view",
    "/crm/sales": ["sales.view", "sales.manage"],
    "/crm/sales-areas": "sales.manage",
    "/crm/sales/performance": "sales.manage",
    "/crm/teams": ["teams.view", "teams.manage"],
    "/crm/orders": "orders.view",
    "/crm/invoices": "invoices.view",
    "/crm/payments": "payments.view",
    "/crm/collection-schedules": ["collections.view", "collections.manage"],
    "/crm/visits": ["visits.view", "visits.manage"],
    "/crm/visit-schedules": ["visits.view", "visits.manage"],
    "/crm/visits/per-sales": "reports.visits.per_sales",
    "/crm/visits/per-period": "reports.visits.per_period",
    "/crm/deliveries": "deliveries.view",
    "/crm/reports": "reports.view",
    "/crm/users": "users.view",
    "/crm/roles": "roles.view",
    "/settings/company": "company.view",
    "/audit-logs": "audit_logs.view",
};

function hasPermission(
    permissions: Record<string, boolean>,
    href: string,
): boolean {
    const permission = permissionByHref[href];

    if (permissions["*"] === true || permissions.all === true) {
        return true;
    }

    if (!permission) {
        return true;
    }

    const required = Array.isArray(permission) ? permission : [permission];

    return required.some((name) => permissions[name] === true);
}

function filterSidebarSections(
    sections: SidebarSection[],
    permissions: Record<string, boolean>,
): SidebarSection[] {
    return sections
        .map((section) => ({
            ...section,
            items: section.items.filter((item) =>
                hasPermission(permissions, String(item.href)),
            ),
        }))
        .filter((section) => section.items.length > 0);
}

function permissionAwareSections(
    role: RoleSlug,
    permissions: Record<string, boolean>,
): SidebarSection[] {
    const sections = roleItems(role);

    return filterSidebarSections(sections, permissions);
}

function roleItems(role: RoleSlug): SidebarSection[] {
    if (role === "platform-owner") {
        return [
            { items: platformOverviewItems, label: "Overview" },
            { items: platformCompanyItems, label: "Manajemen Perusahaan" },
            { items: platformUserItems, label: "Manajemen Pengguna" },
            { items: platformReportItems, label: "Laporan Platform" },
            {
                items: [
                    {
                        title: "Pengaturan Platform",
                        href: "/platform/settings",
                        icon: Settings2,
                    },
                ],
                label: "Pengaturan",
            },
        ];
    }

    if (role === "admin") {
        return [
            { items: overviewItems, label: "Overview" },
            {
                items: [
                    ...customerItems,
                    ...productItems,
                    ...salesItems,
                    ...areaItems,
                ],
                label: "Master Data",
            },
            { items: commerceItems, label: "Transaksi" },
            { items: financeItems, label: "Finance" },
            { items: visitItems, label: "Kunjungan" },
            { items: deliveryItems, label: "Pengiriman" },
            { items: reportItems, label: "Laporan" },
            { items: companyAdminItems, label: "Pengaturan" },
            { items: integrationItems, label: "Integrasi" },
        ];
    }

    if (role === "manager") {
        return [
            { items: overviewItems, label: "Overview" },
            {
                items: [
                    ...customerViewItems,
                    ...productViewItems,
                    ...salesItems,
                    ...areaItems,
                ],
                label: "Master Data",
            },
            { items: commerceItems, label: "Transaksi" },
            { items: financeItems, label: "Finance" },
            { items: visitItems, label: "Kunjungan" },
            { items: reportItems, label: "Laporan" },
        ];
    }

    if (role === "supervisor") {
        return [
            { items: overviewItems, label: "Overview" },
            {
                items: [...salesItems, ...productViewItems],
                label: "Sales & Team",
            },
            { items: customerViewItems, label: "Customer" },
            { items: visitItems, label: "Kunjungan" },
            { items: commerceItems, label: "Order" },
            {
                items: [
                    {
                        title: "Laporan",
                        href: "/crm/reports",
                        icon: BarChart3,
                    },
                ],
                label: "Laporan",
            },
        ];
    }

    if (role === "admin-pengiriman") {
        return [
            { items: dashboardOnlyItems, label: "Overview" },
            { items: commerceItems, label: "Order" },
            {
                items: [
                    {
                        title: "Invoice",
                        href: "/crm/invoices",
                        icon: Receipt,
                    },
                ],
                label: "Finance",
            },
            { items: deliveryItems, label: "Pengiriman" },
        ];
    }

    if (role === "pengiriman") {
        return [
            { items: dashboardOnlyItems, label: "Overview" },
            {
                items: [
                    {
                        title: "Tugas Saya",
                        href: "/crm/deliveries",
                        icon: Truck,
                    },
                ],
                label: "Pengiriman",
            },
        ];
    }

    return [{ items: overviewItems, label: "Overview" }];
}

/*
|--------------------------------------------------------------------------
| APP SIDEBAR COMPONENT
|--------------------------------------------------------------------------
*/

export function AppSidebar() {
    const { auth, tenant } = usePage().props as {
        auth: {
            user?: {
                role?: {
                    slug?: string;
                    name?: string;
                    permissions?: Record<string, boolean> | null;
                } | null;
                is_platform_admin?: boolean;
            };
        };
        tenant?: {
            nama?: string;
        } | null;
    };

    const rawRole = auth.user?.role?.slug ?? "";
    const role = rawRole === "administrator" ? "admin" : rawRole;
    const permissions = auth.user?.role?.permissions ?? {};
    const sections =
        role === "platform-owner" || role === "admin"
            ? roleItems(role)
            : permissionAwareSections(role, permissions);
    const homeHref =
        role === "platform-owner" ? "/platform/dashboard" : dashboard();

    return (
        <Sidebar
            collapsible="icon"
            variant="sidebar"
            className="border-r border-white/10 bg-[#102c4d] text-white"
        >
            <SidebarHeader className="sticky top-0 z-10 border-b border-white/10 bg-[#102c4d]/80 backdrop-blur-md px-2 py-3 group-data-[collapsible=icon]:px-0">
                <SidebarMenu>
                    <SidebarMenuItem>
                        <SidebarMenuButton
                            size="lg"
                            asChild
                            className="h-12 rounded-xl px-2 text-white hover:bg-white/5 hover:text-white data-[state=open]:bg-white/5 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:mx-auto group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:p-0"
                        >
                            <Link
                                href={homeHref}
                                prefetch
                                className="flex items-center justify-center"
                            >
                                <AppLogo />
                            </Link>
                        </SidebarMenuButton>
                    </SidebarMenuItem>

                    <SidebarMenuItem className="mt-2">
                        <div className="flex h-10 min-h-10 items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:mx-auto group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:gap-0 group-data-[collapsible=icon]:p-0 group-data-[collapsible=icon]:border-none group-data-[collapsible=icon]:bg-transparent">
                            <div className="relative flex items-center justify-center">
                                <Building2 className="size-4 shrink-0 text-slate-300" />
                                <span className="absolute -top-1 -right-1 hidden h-2 w-2 group-data-[collapsible=icon]:flex">
                                    <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75"></span>
                                    <span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-500"></span>
                                </span>
                            </div>

                            <span className="min-w-0 flex-1 truncate text-xs font-semibold text-slate-100 group-data-[collapsible=icon]:hidden">
                                {tenant?.nama || "Perusahaan"}
                            </span>

                            <span className="relative flex h-2 w-2 group-data-[collapsible=icon]:hidden">
                                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75"></span>
                                <span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-500"></span>
                            </span>
                        </div>
                    </SidebarMenuItem>
                </SidebarMenu>
            </SidebarHeader>

            <SidebarContent className="overflow-y-auto gap-0 bg-[#102c4d] py-2 group-data-[collapsible=icon]:scrollbar-none group-data-[collapsible=icon]:[-ms-overflow-style:none] group-data-[collapsible=icon]:[&::-webkit-scrollbar]:hidden">
                {sections.map((section) => (
                    <NavMain
                        key={section.label}
                        items={section.items}
                        label={section.label}
                    />
                ))}
            </SidebarContent>

            <SidebarFooter className="sticky bottom-0 z-10 border-t border-white/10 bg-[#102c4d]/80 backdrop-blur-md px-3 py-3 text-xs text-slate-300 group-data-[collapsible=icon]:px-0">
                <div className="flex items-center justify-between group-data-[collapsible=icon]:justify-center">
                    {/* System Status Indicator */}
                    <div className="flex items-center gap-2">
                        <span className="relative flex h-2 w-2">
                            <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75"></span>
                            <span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-500"></span>
                        </span>
                        <span className="font-mono text-[11px] font-medium text-slate-300 group-data-[collapsible=icon]:hidden">
                            Minanga v1.0.0
                        </span>
                    </div>

                    {/* Quick Link / Icon Actions */}
                    <div className="flex items-center gap-2 group-data-[collapsible=icon]:hidden">
                        <a
                            href="/docs"
                            title="Dokumentasi"
                            className="rounded-md p-1 hover:bg-white/10 hover:text-white transition"
                        >
                            <HelpCircle className="h-3.5 w-3.5" />
                        </a>
                    </div>
                </div>
            </SidebarFooter>
        </Sidebar>
    );
}
