'use client';
import { createContext, useContext, ReactNode } from 'react';
import { useAuth, UserRole } from './authContext';

export type RBACRole = 'superadmin' | 'hr_manager' | 'hr_officer' | 'dept_manager' | 'employee' | 'committee';

export type ModuleKey = 'dashboard' | 'employees' | 'leave' | 'training' | 'disciplinary' | 'termination' | 'performance' | 'payroll' | 'grading' | 'recruitment' | 'analytics' | 'setup';

export type Permission = 'full' | 'view' | 'create_edit' | 'team_only' | 'self_only' | 'assigned_only' | 'none';

const ROLE_PERMISSIONS: Record<RBACRole, Record<ModuleKey, Permission>> = {
  superadmin: {
    dashboard: 'full', employees: 'full', leave: 'full', training: 'full',
    disciplinary: 'full', termination: 'full', performance: 'full',
    payroll: 'full', grading: 'full', recruitment: 'full', analytics: 'full', setup: 'full',
  },
  hr_manager: {
    dashboard: 'full', employees: 'view', leave: 'full', training: 'full',
    disciplinary: 'full', termination: 'full', performance: 'full',
    payroll: 'view', grading: 'create_edit', recruitment: 'full', analytics: 'full', setup: 'none',
  },
  hr_officer: {
    dashboard: 'full', employees: 'none', leave: 'view', training: 'create_edit',
    disciplinary: 'view', termination: 'view', performance: 'view',
    payroll: 'none', grading: 'view', recruitment: 'view', analytics: 'view', setup: 'none',
  },
  dept_manager: {
    dashboard: 'team_only', employees: 'none', leave: 'team_only', training: 'team_only',
    disciplinary: 'team_only', termination: 'view', performance: 'team_only',
    payroll: 'none', grading: 'none', recruitment: 'none', analytics: 'team_only', setup: 'none',
  },
  employee: {
    dashboard: 'self_only', employees: 'none', leave: 'self_only', training: 'self_only',
    disciplinary: 'self_only', termination: 'none', performance: 'self_only',
    payroll: 'self_only', grading: 'none', recruitment: 'none', analytics: 'none', setup: 'none',
  },
  committee: {
    dashboard: 'none', employees: 'none', leave: 'none', training: 'none',
    disciplinary: 'assigned_only', termination: 'none', performance: 'none',
    payroll: 'none', grading: 'none', recruitment: 'none', analytics: 'none', setup: 'none',
  },
};

export const ROLE_LABELS: Record<RBACRole, string> = {
  superadmin: 'HR Super Admin',
  hr_manager: 'HR Manager',
  hr_officer: 'HR Officer',
  dept_manager: 'Department Manager',
  employee: 'Employee',
  committee: 'Committee Member',
};

export const ROLE_COLORS: Record<RBACRole, string> = {
  superadmin: 'bg-purple-100 text-purple-700',
  hr_manager: 'bg-blue-100 text-blue-700',
  hr_officer: 'bg-teal-100 text-teal-700',
  dept_manager: 'bg-amber-100 text-amber-700',
  employee: 'bg-gray-100 text-gray-700',
  committee: 'bg-red-100 text-red-700',
};

function mapAuthRoleToRBAC(role: UserRole): RBACRole {
  if (role === 'admin') return 'superadmin';
  if (role === 'hr') return 'hr_manager';
  return 'employee';
}

interface RBACContextType {
  rbacRole: RBACRole;
  can: (module: ModuleKey, permission?: Permission) => boolean;
  getPermission: (module: ModuleKey) => Permission;
  allRoles: RBACRole[];
}

const RBACContext = createContext<RBACContextType | null>(null);

export function RBACProvider({ children }: { children: ReactNode }) {
  const { user } = useAuth();

  const storedRole = typeof window !== 'undefined' ? localStorage.getItem('uwezo_rbac_role') : null;
  const rbacRole: RBACRole = (storedRole as RBACRole) || (user ? mapAuthRoleToRBAC(user.role) : 'employee');

  const getPermission = (module: ModuleKey): Permission => {
    return ROLE_PERMISSIONS[rbacRole]?.[module] ?? 'none';
  };

  const can = (module: ModuleKey, permission: Permission = 'view'): boolean => {
    const p = getPermission(module);
    if (p === 'full') return true;
    if (p === 'none') return false;
    if (permission === 'view') return ['view', 'create_edit', 'team_only', 'self_only', 'assigned_only'].includes(p);
    if (permission === 'create_edit') return ['full', 'create_edit'].includes(p);
    return p === permission;
  };

  return (
    <RBACContext.Provider value={{ rbacRole, can, getPermission, allRoles: Object.keys(ROLE_PERMISSIONS) as RBACRole[] }}>
      {children}
    </RBACContext.Provider>
  );
}

export function useRBAC() {
  const ctx = useContext(RBACContext);
  if (!ctx) throw new Error('useRBAC must be used within RBACProvider');
  return ctx;
}
