"use client";

import * as React from "react";
import {
    Archive,
    Bold,
    Bolt,
    BookCheck,
    BookMarked,
    Command,
    DatabaseBackup,
    FileKey2,
    Flag,
    FolderArchive,
    Frame,
    GalleryVertical,
    Home,
    LifeBuoy,
    NotepadText,
    Scale,
    Send,
    SquareTerminal,
} from "lucide-react";

import { NavMain } from "@/components/nav-main";
import { NavSecondary } from "@/components/nav-secondary";
import { NavUser } from "@/components/nav-user";
import {
    Sidebar,
    SidebarContent,
    SidebarFooter,
    SidebarHeader,
    SidebarMenu,
    SidebarMenuButton,
    SidebarMenuItem,
} from "@/components/ui/sidebar";
import { Link, usePage } from "@inertiajs/react";
import { PageProps } from "@/types";
import hasAnyPermission from "@/utils/hasAnyPermission";

const data = {
    user: {
        name: "shadcn",
        email: "m@example.com",
        avatar: "/avatars/shadcn.jpg",
    },
    navMain: [
        {
            title: "Dashboard",
            url: "/dashboard",
            permissions: ["Dashboard.index"],
            icon: Home,
        },
        {
            title: "Pelaporan",
            url: "/admin/pelaporan",
            permissions: ["Pelaporan.index"],
            icon: BookMarked,
        },
        {
            title: "Verifikasi Pelaporan",
            url: "/admin/verifikasi",
            permissions: ["Verifikasi.index"],
            icon: BookCheck,
        },
        {
            title: "Penegakan Hukum",
            url: "/admin/hukum",
            permissions: ["Hukum.index"],
            icon: Scale,
        },
        {
            title: "Perizinan Lingkungan",
            url: "/admin/perizinan_lingkungan",
            permissions: ["Perizinan.index"],
            icon: FileKey2,
        },
        {
            title: "History Perusahaan",
            url: "/admin/history_perusahaan",
            permissions: ["History.index"],
            icon: GalleryVertical,
        },
        {
            title: "Post",
            url: "/admin/post",
            permissions: ["Post.index"],
            icon: Frame,
        },
        {
            title: "Reporting",
            url: "#",
            icon: Flag,
            isActive: true,
            items: [
                {
                    title: "Rekapitulasi",
                    url: "/admin/rekap",
                },
                {
                    title: "SKL & SPL",
                    url: "/admin/skl-spl",
                },
                {
                    title: "Daftar Perusahaan",
                    url: "/admin/daftar-perusahaan",
                },
                {
                    title: "SKL",
                    url: "/admin/skl",
                },
                {
                    title: "SPL",
                    url: "/admin/spl",
                },
            ],
        },
        {
            title: "Data Master",
            url: "#",
            icon: FolderArchive,
            isActive: true,
            items: [
                {
                    title: "Kategori Post",
                    url: "/admin/kategori",
                    permissions: ["Kategori.index"],
                },
                {
                    title: "Sub Kategori Post",
                    url: "/admin/subkategori",
                    permissions: ["SubKategori.index"],
                },
                {
                    title: "Dinas LH",
                    url: "/admin/verifikator",
                    permissions: ["Verifikator.index"],
                },
                {
                    title: "Jenis Kegiatan",
                    url: "/admin/jeniskegiatan",
                    permissions: ["JenisKegiatan.index"],
                },
                {
                    title: "Jenis Dokumen Izin",
                    url: "/admin/jenisdokil",
                    permissions: ["JenisDokil.index"],
                },
                {
                    title: "Data Perusahaan",
                    url: "/admin/perusahaan",
                    permissions: ["Perusahaan.index"],
                },
                {
                    title: "History Kegiatan",
                    url: "/admin/historykegiatan",
                    permissions: ["HistoryKegiatan.index"],
                },
                {
                    title: "Jenis Sanksi",
                    url: "/admin/jenissanksi",
                    permissions: ["JenisSanksi.index"],
                },
                {
                    title: "Status Penaatan",
                    url: "/admin/penaatan",
                    permissions: ["Penaatan.index"],
                },
            ],
        },
        {
            title: "Pengaturan",
            url: "#",
            icon: Bolt,
            isActive: true,
            items: [
                {
                    title: "Pengguna",
                    url: "/admin/pengguna",
                    permissions: ["Pengguna.index"],
                },
                {
                    title: "Kelompok Pengguna",
                    url: "/admin/roles",
                    permissions: ["Role.index"],
                },
            ],
        },
    ],
    navSecondary: [
        {
            title: "Tentang",
            url: "/admin/tentang",
            icon: LifeBuoy,
            permissions: ["Tentang.index"],
        },
        {
            title: "Catatan Sistem",
            url: "#",
            icon: NotepadText,
            permissions: ["Catatan.index"],
        },
        {
            title: "Backup",
            url: "#",
            icon: Archive,
            permissions: ["Backup.index"],
        },
        {
            title: "Restore",
            url: "#",
            icon: DatabaseBackup,
            permissions: ["Restore.index"],
        },
    ],
};

export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
    const { auth } = usePage<PageProps>().props;
    const userPermissions = auth?.user?.permissions ?? [];

    const filterMenu = (menu) => {
        return menu
            .map((item) => {
                if (item.items) {
                    const filteredItems = item.items.filter((subItem) =>
                        subItem.permissions
                            ? hasAnyPermission(
                                  Array.isArray(subItem.permissions)
                                      ? subItem.permissions
                                      : Object.keys(subItem.permissions) // Pastikan selalu array
                              )
                            : true
                    );

                    if (filteredItems.length > 0) {
                        return { ...item, items: filteredItems };
                    }
                    return null;
                }

                if (item.permissions) {
                    // **PERBAIKAN UTAMA**: Pastikan item.permissions selalu dalam bentuk array
                    const permissionsArray = Array.isArray(item.permissions)
                        ? item.permissions
                        : Object.keys(item.permissions);

                    const hasPermission = hasAnyPermission(permissionsArray);

                    return hasPermission ? item : null;
                }

                return item;
            })
            .filter(Boolean);
    };

    const navMain = filterMenu(data.navMain);
    const navSecondary = filterMenu(data.navSecondary);

    return (
        <Sidebar variant="inset" {...props}>
            <SidebarHeader>
                <SidebarMenu>
                    <SidebarMenuItem>
                        <SidebarMenuButton size="lg" asChild>
                            {/* {hasAnyPermission(["Dashboard.index"]) && ( */}
                            <Link href={route("dashboard")}>
                                <div className="flex aspect-square size-8 items-center justify-center rounded-lg text-sidebar-primary-foreground">
                                    {/* <Command className="size-4" /> */}
                                    <img
                                        src="/assets/logo_skl.svg"
                                        alt="Logo"
                                        className="w-12 h-12 md:w-16 md:h-16"
                                    />
                                </div>
                                <div className="grid flex-1 text-left text-sm leading-tight">
                                    <span className="truncate font-semibold">
                                        SKL
                                    </span>
                                    <span className="truncate text-xs">
                                        Status Ketaatan Lingkungan
                                    </span>
                                </div>
                            </Link>
                            {/* )} */}
                        </SidebarMenuButton>
                    </SidebarMenuItem>
                </SidebarMenu>
            </SidebarHeader>
            <SidebarContent>
                <NavMain items={navMain} />
                <NavSecondary items={navSecondary} className="mt-auto" />
            </SidebarContent>
            <SidebarFooter>
                <NavUser user={auth.user} />
            </SidebarFooter>
        </Sidebar>
    );
}
