import React from 'react';
import {
  LayoutDashboard,
  Server,
  Wrench,
  BarChart3,
  ShieldCheck,
  FileText,
  Building2,
  Briefcase,
  Box,
  ClipboardCheck,
  CalendarDays,
  Settings,
  Activity,
} from 'lucide-react';
import type { IUser } from '../../types';
import { hasPermission, hasAnyPermission, PERMISSION } from '../../utils/permissions';

export interface MenuItemConfig {
  path: string;
  label: string;
  iconComponent: React.ComponentType<{ size?: number }>;
  /** Chỉ hiện khi user có quyền này */
  requiredPermission?: string;
  /** Chỉ hiện khi user có ít nhất một quyền */
  requiredAnyPermissions?: string[];
}

export interface MenuSubgroupConfig {
  key: string;
  /** Tiêu đề nhóm con (uppercase trong UI); null nếu không có */
  subheading: string | null;
  items: MenuItemConfig[];
}

/** Tổng quan — cấp cao nhất */
export const OVERVIEW_ITEMS: MenuItemConfig[] = [
  { path: '/', label: 'Dashboard', iconComponent: LayoutDashboard },
  { path: '/om-dashboard', label: 'Quản lý O&M', iconComponent: Activity },
  { path: '/projects', label: 'Quản lý dự án', iconComponent: Building2 },
];

/** Điều hướng theo ngữ cảnh dự án đang chọn */
export const CURRENT_PROJECT_SUBGROUPS: MenuSubgroupConfig[] = [
  {
    key: 'cp-overview',
    subheading: null,
    items: [{ path: '/dashboard-project', label: 'Tổng quan dự án', iconComponent: BarChart3 }],
  },
  {
    key: 'cp-am',
    subheading: 'QUẢN LÝ TÀI SẢN',
    items: [
      { path: '/assets', label: 'Hồ sơ tài sản', iconComponent: Server },
      { path: '/contracts', label: 'Hợp đồng & Pháp lý', iconComponent: Briefcase },
    ],
  },
  {
    key: 'cp-om',
    subheading: 'VẬN HÀNH & BẢO TRÌ',
    items: [
      { path: '/operations', label: 'Phiếu sự cố (Ticket)', iconComponent: Wrench },
      { path: '/work-orders', label: 'Công việc (Work Order)', iconComponent: ClipboardCheck },
      { path: '/schedule', label: 'Lịch bảo trì (PM)', iconComponent: CalendarDays },
    ],
  },
  {
    key: 'cp-extra',
    subheading: null,
    items: [
      { path: '/inventory', label: 'Kho & Vật tư', iconComponent: Box },
      { path: '/compliance', label: 'HSE & Tuân thủ', iconComponent: ShieldCheck },
    ],
  },
];

export const FINANCE_ITEMS: MenuItemConfig[] = [
  { path: '/finance', label: 'Tài chính & ROI', iconComponent: BarChart3 },
  { path: '/reports', label: 'Báo cáo', iconComponent: FileText },
];

export const SYSTEM_ITEMS: MenuItemConfig[] = [
  // "Quản trị & Người dùng" (/governance) removed — user management moved to CSM.
  {
    path: '/settings',
    label: 'Cài đặt',
    iconComponent: Settings,
    requiredAnyPermissions: [PERMISSION.config_system, PERMISSION.manage_users],
  },
];

/** @deprecated Giữ MENU_GROUPS_CONFIG cho mã legacy nếu cần; ưu tiên OVERVIEW_ITEMS + CURRENT_PROJECT_SUBGROUPS + … */
export const MENU_GROUPS_CONFIG: { key: string; title: string; items: MenuItemConfig[] }[] = [];

export interface MenuItem {
  path: string;
  label: string;
  icon: React.ReactNode;
}

export interface MenuSubgroup {
  key: string;
  subheading: string | null;
  items: MenuItem[];
}

function itemVisibleForUser(item: MenuItemConfig, user: IUser | null): boolean {
  if (item.requiredPermission) {
    return hasPermission(user, item.requiredPermission);
  }
  if (item.requiredAnyPermissions?.length) {
    return hasAnyPermission(user, item.requiredAnyPermissions);
  }
  return true;
}

function filterItems(items: MenuItemConfig[], user: IUser | null): MenuItem[] {
  return items
    .filter((item) => itemVisibleForUser(item, user))
    .map((item) => ({
      path: item.path,
      label: item.label,
      icon: React.createElement(item.iconComponent, { size: 18 }),
    }));
}

function filterCurrentProjectSubgroups(user: IUser | null): MenuSubgroup[] {
  return CURRENT_PROJECT_SUBGROUPS.map((sub) => ({
    key: sub.key,
    subheading: sub.subheading,
    items: filterItems(sub.items, user),
  })).filter((sub) => sub.items.length > 0);
}

export interface SidebarSections {
  overview: MenuItem[];
  currentProjectSubgroups: MenuSubgroup[];
  finance: MenuItem[];
  system: MenuItem[];
}

/** Menu sidebar sau khi lọc theo RBAC */
export const getSidebarSectionsForUser = (user: IUser | null): SidebarSections => ({
  overview: filterItems(OVERVIEW_ITEMS, user),
  currentProjectSubgroups: filterCurrentProjectSubgroups(user),
  finance: filterItems(FINANCE_ITEMS, user),
  system: filterItems(SYSTEM_ITEMS, user),
});

export const DEFAULT_EXPANDED_GROUPS: Record<string, boolean> = {
  overview: true,
  finance: false,
  system: true,
};

/** @deprecated Dùng getSidebarSectionsForUser */
export interface MenuGroup {
  key: string;
  title: string;
  items: MenuItem[];
}

/** @deprecated Dùng getSidebarSectionsForUser */
export const getMenuGroupsForUser = (user: IUser | null): MenuGroup[] => {
  const sections = getSidebarSectionsForUser(user);
  const groups: MenuGroup[] = [
    ...(sections.overview.length ? [{ key: 'overview', title: 'TỔNG QUAN', items: sections.overview }] : []),
    ...(sections.currentProjectSubgroups.some((s) => s.items.length)
      ? [
          {
            key: 'current-project',
            title: 'DỰ ÁN HIỆN TẠI',
            items: sections.currentProjectSubgroups.flatMap((s) => s.items),
          },
        ]
      : []),
    ...(sections.finance.length ? [{ key: 'finance', title: 'TÀI CHÍNH & BÁO CÁO', items: sections.finance }] : []),
    ...(sections.system.length ? [{ key: 'system', title: 'HỆ THỐNG', items: sections.system }] : []),
  ];
  return groups;
};
