"use client";

import { useEffect, useState } from 'react';
import {
    Square2StackIcon,
    ShieldCheckIcon,
    ServerIcon,
    CpuChipIcon,
    DocumentTextIcon,
    Cog6ToothIcon,
    ClipboardDocumentCheckIcon,
    UserGroupIcon,
    EyeIcon,
    KeyIcon,
    CheckBadgeIcon,
} from '@heroicons/react/24/outline';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import clsx from 'clsx';
import api from '../../../lib/api';

type Role = 'admin' | 'editor' | 'readonly' | null;

// `requires` — minimum role needed. Item is hidden when current user has less.
// readonly < editor < admin
type NavItem = {
    name: string;
    href: string;
    icon: any;
    requires?: 'admin' | 'editor';
};

const navigation: NavItem[] = [
    { name: 'Dashboard', href: '/', icon: Square2StackIcon },
    { name: 'Vulnerabilities', href: '/vulnerabilities', icon: ShieldCheckIcon },
    { name: 'Assets', href: '/assets', icon: ServerIcon },
    { name: 'Compliance', href: '/compliance', icon: CheckBadgeIcon },
    { name: 'Scan Jobs', href: '/scans', icon: CpuChipIcon, requires: 'editor' },
];

const management: NavItem[] = [
    { name: 'Groups', href: '/groups', icon: UserGroupIcon, requires: 'admin' },
    { name: 'Policies', href: '/policies', icon: ClipboardDocumentCheckIcon, requires: 'editor' },
    { name: 'Reports', href: '/reports', icon: DocumentTextIcon },
    { name: 'Notifications', href: '/notifications', icon: DocumentTextIcon },
    { name: 'Audit Logs', href: '/admin/audit-logs', icon: EyeIcon, requires: 'admin' },
    { name: 'Auth Providers', href: '/admin/auth', icon: KeyIcon, requires: 'admin' },
    { name: 'Settings', href: '/settings', icon: Cog6ToothIcon },
];

const RANK: Record<Exclude<Role, null>, number> = {
    readonly: 0,
    editor: 1,
    admin: 2,
};

function hasRole(current: Role, required?: 'admin' | 'editor'): boolean {
    if (!required) return true;
    if (!current) return false;
    return RANK[current] >= RANK[required];
}

export default function Navigation() {
    const pathname = usePathname();
    const [role, setRole] = useState<Role>(null);
    const [loaded, setLoaded] = useState(false);

    useEffect(() => {
        api.get('/auth/me')
            .then((r) => {
                const v = String(r.data?.role || '').toLowerCase();
                if (v === 'admin' || v === 'editor' || v === 'readonly') {
                    setRole(v as Role);
                }
            })
            .catch(() => setRole(null))
            .finally(() => setLoaded(true));
    }, []);

    const renderNavList = (items: NavItem[]) => {
        const visible = items.filter((it) => hasRole(role, it.requires));
        if (visible.length === 0) return null;
        return (
            <ul role="list" className="-mx-2 space-y-1">
                {visible.map((item) => {
                    const isActive = pathname === item.href;
                    return (
                        <li key={item.name}>
                            <Link
                                href={item.href}
                                className={clsx(
                                    isActive
                                        ? 'bg-gray-800 text-vulncheck-blue group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold'
                                        : 'text-gray-400 hover:text-white hover:bg-gray-800 group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold'
                                )}
                            >
                                <item.icon
                                    className={clsx(
                                        isActive ? 'text-vulncheck-blue' : 'text-gray-400 group-hover:text-white',
                                        'h-6 w-6 shrink-0'
                                    )}
                                    aria-hidden="true"
                                />
                                {item.name}
                            </Link>
                        </li>
                    );
                })}
            </ul>
        );
    };

    // Avoid menu-flicker on first paint before /auth/me resolves: render
    // only the always-visible items until we know the role.
    const effectiveNav = loaded ? navigation : navigation.filter((it) => !it.requires);
    const effectiveMgmt = loaded ? management : management.filter((it) => !it.requires);

    return (
        <nav className="flex flex-1 flex-col gap-8 mt-8 px-6">
            <div>
                <div className="text-xs font-semibold leading-6 text-gray-400 uppercase tracking-wider mb-2 pl-2">Overview</div>
                {renderNavList(effectiveNav)}
            </div>
            {effectiveMgmt.some((it) => hasRole(role, it.requires)) && (
                <div>
                    <div className="text-xs font-semibold leading-6 text-gray-400 uppercase tracking-wider mb-2 pl-2">Management</div>
                    {renderNavList(effectiveMgmt)}
                </div>
            )}
        </nav>
    );
}
