import {
    LayoutDashboard,
    CheckSquare,
    Home,
    Sprout,
    Clock,
    Package,
    CalendarDays,
    Shield,
    Settings,
    Fingerprint,
    BarChart3,
    Thermometer,
    DollarSign,
    Brain,
    Users,
    FileText,
    ClipboardList,
    Grid3X3,
    Cloud,
    type LucideIcon
} from 'lucide-react';

/**
 * Navigation configuration with RBAC support
 */

export type UserRole = 'VIEWER' | 'STAFF' | 'GROWER' | 'MANAGER' | 'ADMIN' | 'OWNER';

// Role hierarchy for permission checking (higher index = more access)
const ROLE_HIERARCHY: UserRole[] = ['VIEWER', 'STAFF', 'GROWER', 'MANAGER', 'ADMIN', 'OWNER'];

export interface NavItem {
    id: string;
    label: string;
    path: string;
    icon: LucideIcon;
    shortLabel?: string; // For mobile bottom nav
    minRole?: UserRole; // Minimum role required to see this item
    badge?: 'pending' | 'count'; // Dynamic badge type
}

export interface NavSection {
    id: string;
    label: string;
    minRole?: UserRole;
    items: NavItem[];
}

/**
 * Check if a user role has access to a resource requiring minRole
 */
export function hasAccess(userRole: string, minRole?: UserRole): boolean {
    if (!minRole) return true; // No restriction

    const userIndex = ROLE_HIERARCHY.indexOf(userRole.toUpperCase() as UserRole);
    const minIndex = ROLE_HIERARCHY.indexOf(minRole);

    // If user role not found in hierarchy, default to no access
    if (userIndex === -1) return false;

    return userIndex >= minIndex;
}

/**
 * Navigation configuration - grouped by function
 */
export const NAV_SECTIONS: NavSection[] = [
    {
        id: 'operations',
        label: 'Operations',
        items: [
            { id: 'dashboard', label: 'Dashboard', shortLabel: 'Home', path: '/', icon: LayoutDashboard },
            { id: 'walkthrough', label: 'Daily Walkthrough', shortLabel: 'Daily', path: '/walkthrough', icon: CheckSquare },
            { id: 'quick-actions', label: 'Quick Actions', shortLabel: 'Quick', path: '/touch-points', icon: Fingerprint },
            { id: 'tasks', label: 'Tasks', path: '/tasks', icon: CalendarDays },
        ]
    },
    {
        id: 'cultivation',
        label: 'Cultivation',
        items: [
            { id: 'rooms', label: 'Rooms', path: '/rooms', icon: Home },
            { id: 'batches', label: 'Batches', path: '/batches', icon: Sprout },
            { id: 'ipm', label: 'IPM Dashboard', shortLabel: 'IPM', path: '/ipm', icon: Shield },
            { id: 'environment', label: 'Environment', path: '/environment', icon: Thermometer, minRole: 'STAFF' },
        ]
    },
    {
        id: 'inventory',
        label: 'Inventory',
        minRole: 'STAFF',
        items: [
            { id: 'supplies', label: 'Supplies', path: '/supplies', icon: Package },
        ]
    },
    {
        id: 'workforce',
        label: 'Workforce',
        minRole: 'STAFF',
        items: [
            { id: 'timeclock', label: 'Time Clock', path: '/timeclock', icon: Clock },
        ]
    },
    {
        id: 'visitors',
        label: 'Visitors',
        minRole: 'MANAGER',
        items: [
            { id: 'visitors', label: 'Visitor Management', path: '/visitors', icon: Users },
        ]
    },
    {
        id: 'analytics',
        label: 'Analytics',
        minRole: 'STAFF',
        items: [
            { id: 'reports', label: 'Reports', path: '/reports', icon: BarChart3 },
            { id: 'financial', label: 'Financial', path: '/financial', icon: DollarSign, minRole: 'MANAGER' },
            { id: 'insights', label: 'AI Insights', path: '/insights', icon: Brain, minRole: 'MANAGER' },
        ]
    },
    {
        id: 'compliance',
        label: 'Compliance',
        minRole: 'MANAGER',
        items: [
            { id: 'audit', label: 'Audit Log', path: '/compliance/audit', icon: ClipboardList },
            { id: 'documents', label: 'SOP Library', path: '/compliance/documents', icon: FileText },
            { id: 'metrc', label: 'METRC Integration', path: '/metrc', icon: Cloud, minRole: 'MANAGER' },
            { id: 'facility-3d', label: '3D Facility View', path: '/facility/3d', icon: Grid3X3, minRole: 'MANAGER' },
            { id: 'layout', label: 'Layout Designer', path: '/layout-designer', icon: Grid3X3, minRole: 'ADMIN' },
        ]
    },
    {
        id: 'admin',
        label: 'Administration',
        minRole: 'ADMIN',
        items: [
            { id: 'roles', label: 'Roles & Permissions', path: '/roles', icon: Shield },
            { id: 'settings', label: 'Settings', path: '/settings', icon: Settings },
        ]
    }
];

/**
 * Get all navigation items flattened (for search, command palette, etc.)
 */
export function getAllNavItems(): NavItem[] {
    return NAV_SECTIONS.flatMap(section => section.items);
}

/**
 * Get navigation items filtered by user role
 */
export function getFilteredNavSections(userRole: string): NavSection[] {
    return NAV_SECTIONS
        .filter(section => hasAccess(userRole, section.minRole))
        .map(section => ({
            ...section,
            items: section.items.filter(item => hasAccess(userRole, item.minRole))
        }))
        .filter(section => section.items.length > 0);
}

/**
 * Get primary nav items for mobile bottom bar (max 5)
 */
export function getMobileNavItems(userRole: string): NavItem[] {
    const primaryIds = ['dashboard', 'walkthrough', 'quick-actions', 'tasks'];
    const allItems = getAllNavItems().filter(item => hasAccess(userRole, item.minRole));

    return allItems
        .filter(item => primaryIds.includes(item.id))
        .slice(0, 4); // Leave room for "More" button
}

/**
 * Get current section for a path (for breadcrumbs, highlighting)
 */
export function getCurrentSection(path: string): NavSection | undefined {
    return NAV_SECTIONS.find(section =>
        section.items.some(item => item.path === path)
    );
}

/**
 * Get current nav item for a path
 */
export function getCurrentNavItem(path: string): NavItem | undefined {
    return getAllNavItems().find(item => item.path === path);
}
