'use client';
import { useState } from 'react';
import { ROLE_LABELS, ROLE_COLORS, RBACRole, ModuleKey, Permission } from '../../lib/rbacContext';

const MODULES: { key: ModuleKey; label: string; icon: string }[] = [
  { key: 'dashboard', label: 'Dashboard', icon: 'ri-dashboard-line' },
  { key: 'employees', label: 'Employees', icon: 'ri-team-line' },
  { key: 'leave', label: 'Leave Management', icon: 'ri-calendar-check-line' },
  { key: 'training', label: 'Training & Development', icon: 'ri-graduation-cap-line' },
  { key: 'disciplinary', label: 'Disciplinary Cases', icon: 'ri-scales-3-line' },
  { key: 'termination', label: 'Termination & Turnover', icon: 'ri-user-unfollow-line' },
  { key: 'performance', label: 'Performance Appraisals', icon: 'ri-bar-chart-line' },
  { key: 'payroll', label: 'Payroll', icon: 'ri-money-dollar-circle-line' },
  { key: 'grading', label: 'Categories & Grading', icon: 'ri-medal-line' },
  { key: 'recruitment', label: 'Recruitment', icon: 'ri-briefcase-line' },
  { key: 'analytics', label: 'Analytics & Reports', icon: 'ri-pie-chart-2-line' },
  { key: 'setup', label: 'System Setup', icon: 'ri-tools-line' },
];

const ROLES: RBACRole[] = ['superadmin', 'hr_manager', 'hr_officer', 'dept_manager', 'employee', 'committee'];

const PERMISSION_CONFIG: Record<Permission, { label: string; color: string; bg: string }> = {
  full: { label: 'Full Access', color: 'text-green-700', bg: 'bg-green-100' },
  view: { label: 'View Only', color: 'text-blue-700', bg: 'bg-blue-100' },
  create_edit: { label: 'Create/Edit', color: 'text-purple-700', bg: 'bg-purple-100' },
  team_only: { label: 'Team Only', color: 'text-amber-700', bg: 'bg-amber-100' },
  self_only: { label: 'Self Only', color: 'text-orange-700', bg: 'bg-orange-100' },
  assigned_only: { label: 'Assigned Only', color: 'text-teal-700', bg: 'bg-teal-100' },
  none: { label: 'No Access', color: 'text-gray-400', bg: 'bg-gray-100' },
};

const INITIAL_MATRIX: 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 default function RBACTab() {
  const [matrix, setMatrix] = useState(INITIAL_MATRIX);
  const [selectedRole, setSelectedRole] = useState<RBACRole>('superadmin');
  const [saved, setSaved] = useState(false);
  const [editingCell, setEditingCell] = useState<{ role: RBACRole; module: ModuleKey } | null>(null);

  const handlePermChange = (role: RBACRole, module: ModuleKey, perm: Permission) => {
    setMatrix(m => ({ ...m, [role]: { ...m[role], [module]: perm } }));
    setEditingCell(null);
  };

  const handleSave = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 3000);
  };

  return (
    <div className="space-y-6">
      {saved && (
        <div className="flex items-center gap-2 p-3 bg-green-50 border border-green-200 rounded-xl text-green-700 text-sm">
          <div className="w-5 h-5 flex items-center justify-center"><i className="ri-checkbox-circle-fill text-base"></i></div>
          RBAC permissions saved successfully. Changes will take effect on next login.
        </div>
      )}

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="font-bold text-gray-800">Role-Based Access Control Matrix</h3>
            <p className="text-xs text-gray-500 mt-0.5">Define permissions per role per module. Click any cell to change permission.</p>
          </div>
          <button onClick={handleSave} className="px-5 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
            Save Permissions
          </button>
        </div>

        <div className="flex gap-2 mb-4 flex-wrap">
          {Object.entries(PERMISSION_CONFIG).map(([key, val]) => (
            <span key={key} className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${val.bg} ${val.color}`}>
              {val.label}
            </span>
          ))}
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-gray-100">
                <th className="text-left py-3 px-3 text-xs font-semibold text-gray-500 w-44">Module</th>
                {ROLES.map(role => (
                  <th key={role} className="text-center py-3 px-2 text-xs font-semibold text-gray-600 min-w-28">
                    <span className={`inline-block px-2 py-1 rounded-full text-xs font-medium ${ROLE_COLORS[role]}`}>
                      {ROLE_LABELS[role]}
                    </span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {MODULES.map((mod, i) => (
                <tr key={mod.key} className={i % 2 === 0 ? 'bg-gray-50/50' : 'bg-white'}>
                  <td className="py-3 px-3">
                    <div className="flex items-center gap-2">
                      <div className="w-7 h-7 flex items-center justify-center rounded-lg bg-pink-100">
                        <i className={`${mod.icon} text-sm`} style={{ color: '#b828a0' }}></i>
                      </div>
                      <span className="text-sm font-medium text-gray-700">{mod.label}</span>
                    </div>
                  </td>
                  {ROLES.map(role => {
                    const perm = matrix[role][mod.key];
                    const cfg = PERMISSION_CONFIG[perm];
                    const isEditing = editingCell?.role === role && editingCell?.module === mod.key;
                    return (
                      <td key={role} className="py-3 px-2 text-center">
                        <div className="relative">
                          <button
                            onClick={() => setEditingCell(isEditing ? null : { role, module: mod.key })}
                            className={`inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium cursor-pointer transition-all hover:shadow-sm ${cfg.bg} ${cfg.color}`}
                          >
                            {cfg.label}
                            <i className="ri-arrow-down-s-line text-xs"></i>
                          </button>
                          {isEditing && (
                            <div className="absolute z-20 top-full mt-1 left-1/2 -translate-x-1/2 bg-white rounded-xl shadow-2xl border border-gray-100 p-1 min-w-36">
                              {Object.entries(PERMISSION_CONFIG).map(([key, val]) => (
                                <button
                                  key={key}
                                  onClick={() => handlePermChange(role, mod.key, key as Permission)}
                                  className={`w-full text-left px-3 py-2 rounded-lg text-xs font-medium cursor-pointer hover:bg-gray-50 flex items-center gap-2 ${perm === key ? 'bg-pink-50' : ''}`}
                                >
                                  <span className={`w-2 h-2 rounded-full ${val.bg}`}></span>
                                  {val.label}
                                </button>
                              ))}
                            </div>
                          )}
                        </div>
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="grid grid-cols-3 gap-4">
        {ROLES.map(role => (
          <div key={role} className="bg-white rounded-xl border border-gray-100 p-4">
            <div className="flex items-center gap-2 mb-3">
              <span className={`px-2.5 py-1 rounded-full text-xs font-semibold ${ROLE_COLORS[role]}`}>{ROLE_LABELS[role]}</span>
            </div>
            <div className="space-y-1.5">
              {MODULES.map(mod => {
                const perm = matrix[role][mod.key];
                const cfg = PERMISSION_CONFIG[perm];
                return (
                  <div key={mod.key} className="flex items-center justify-between text-xs">
                    <span className="text-gray-500 truncate mr-2">{mod.label}</span>
                    <span className={`px-1.5 py-0.5 rounded text-xs font-medium whitespace-nowrap ${cfg.bg} ${cfg.color}`}>{cfg.label}</span>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
