import React, { useState } from 'react';
import { ROLES, PERMS } from '../../context/PermissionsContext';

// ─── Mock data ────────────────────────────────────────────────────────────────
const MOCK_USERS_INITIAL = [
  { id:'u1',  name:'Álvaro Romero',  email:'alro65@gmail.com',           role:'OWNER',      status:'ACTIVO',   avatar:'AR', color:'bg-slate-800',   projects:['all'] },
  { id:'u2',  name:'Miguel Castro',  email:'mcastro@arelectronics.com',  role:'ADMIN',      status:'ACTIVO',   avatar:'MC', color:'bg-purple-600',  projects:['all'] },
  { id:'u3',  name:'Paula Soto',     email:'atorres@arelectronics.com',  role:'GERENTE',    status:'ACTIVO',   avatar:'AT', color:'bg-blue-600',    projects:['PRY-001'] },
  { id:'u4',  name:'Ricardo Mora',   email:'rmora@arelectronics.com',    role:'GERENTE',    status:'ACTIVO',   avatar:'RM', color:'bg-blue-700',    projects:['PRY-002'] },
  { id:'u5',  name:'Carmen Vidal',   email:'cvidal@arelectronics.com',   role:'GERENTE',    status:'ACTIVO',   avatar:'CV', color:'bg-blue-500',    projects:['PRY-003'] },
  { id:'u6',  name:'Jorge Salcedo',  email:'jsalcedo@arelectronics.com', role:'GERENTE',    status:'ACTIVO',   avatar:'JS', color:'bg-blue-800',    projects:['PRY-004'] },
  { id:'u7',  name:'María Jiménez',  email:'mjimenez@arelectronics.com', role:'FINANCIERO', status:'ACTIVO',   avatar:'MJ', color:'bg-emerald-600', projects:['all'] },
  { id:'u8',  name:'Carlos Ríos',    email:'crios@arelectronics.com',    role:'CONTADOR',   status:'ACTIVO',   avatar:'CR', color:'bg-teal-600',    projects:['all'] },
  { id:'u9',  name:'Álvaro Romero',   email:'lmendoza@arelectronics.com', role:'INGENIERO',  status:'ACTIVO',   avatar:'LM', color:'bg-orange-600',  projects:['PRY-001','PRY-003'] },
  { id:'u10', name:'Álvaro Romero',   email:'pvargas@arelectronics.com',  role:'SUPERVISOR', status:'ACTIVO',   avatar:'PV', color:'bg-amber-600',   projects:['PRY-002'] },
  { id:'u11', name:'Sandra López',   email:'slopez@arelectronics.com',   role:'TECNICO',    status:'INACTIVO', avatar:'SL', color:'bg-gray-500',    projects:['PRY-001'] },
  { id:'u12', name:'Paula Soto',  email:'fsuarez@arelectronics.com',  role:'INGENIERO',  status:'ACTIVO',   avatar:'FS', color:'bg-orange-500',  projects:['PRY-002','PRY-004'] },
  { id:'u13', name:'Diana Herrera',  email:'dherrera@arelectronics.com', role:'SUPERVISOR', status:'ACTIVO',   avatar:'DH', color:'bg-amber-500',   projects:['PRY-003','PRY-004'] },
];

const MOCK_PROJECTS = [
  { code:'PRY-001', name:'AR-ProjectManagement' },
  { code:'PRY-002', name:'AR-ProjectManagement' },
  { code:'PRY-003', name:'Subestación Eléctrica' },
  { code:'PRY-004', name:'Bodega Industrial Norte' },
];

const ALL_PROJECTS = MOCK_PROJECTS.map(p => p.code);

// ─── Role styling ─────────────────────────────────────────────────────────────
const ROLE_STYLES = {
  OWNER:      'bg-slate-900 text-white',
  ADMIN:      'bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300',
  GERENTE:    'bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300',
  FINANCIERO: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300',
  CONTADOR:   'bg-teal-100 text-teal-800 dark:bg-teal-900/40 dark:text-teal-300',
  INGENIERO:  'bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300',
  SUPERVISOR: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300',
  TECNICO:    'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300',
};

const ROLE_LABELS = {
  OWNER: 'Propietario', ADMIN: 'Administrador', GERENTE: 'Gerente',
  FINANCIERO: 'Dir. Financiero', CONTADOR: 'Contador', INGENIERO: 'Ingeniero',
  SUPERVISOR: 'Supervisor', TECNICO: 'Técnico',
};

// ─── Perms matrix config ──────────────────────────────────────────────────────
const PERM_GROUPS = [
  {
    group: 'Financiero / Contable',
    items: [
      { key: 'CASH_FLOW_ALARM',      label: 'Alarma Cash Flow' },
      { key: 'ACCOUNTING_PAYMENTS',  label: 'Pagos' },
      { key: 'ACCOUNTING_CONTRACTS', label: 'Contratos' },
      { key: 'ACCOUNTING_NOMINA',    label: 'Nómina' },
      { key: 'ACCOUNTING_LIBRO',     label: 'Libro Mayor' },
      { key: 'ACCOUNTING_FLUJO',     label: 'Flujo de Caja' },
      { key: 'BUDGET',               label: 'Presupuesto' },
      { key: 'REPORTS_FINANCIAL',    label: 'Reportes Financieros' },
      { key: 'PROCUREMENT',          label: 'Abastecimiento' },
    ],
  },
  {
    group: 'Gestión de Proyectos',
    items: [
      { key: 'PROJECTS',             label: 'Proyectos' },
      { key: 'TASKS',                label: 'Tareas' },
      { key: 'TEAM',                 label: 'Equipo' },
      { key: 'REPORTS_OPERATIONAL',  label: 'Reportes Operativos' },
    ],
  },
  {
    group: 'Sistema',
    items: [
      { key: 'USERS_ROLES', label: 'Usuarios y Roles' },
      { key: 'SETTINGS',    label: 'Configuración' },
    ],
  },
];

const ROLE_ORDER = ['OWNER','ADMIN','GERENTE','FINANCIERO','CONTADOR','INGENIERO','SUPERVISOR','TECNICO'];

// ─── Empty form ───────────────────────────────────────────────────────────────
const EMPTY_FORM = { name:'', email:'', role:'INGENIERO', projects:[], status:'ACTIVO' };

// ─── Sub-components ───────────────────────────────────────────────────────────
function RoleBadge({ role }) {
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold ${ROLE_STYLES[role] ?? 'bg-gray-100 text-gray-700'}`}>
      {ROLE_LABELS[role] ?? role}
    </span>
  );
}

function Avatar({ initials }) {
  return (
    <div className="w-8 h-8 rounded-full bg-blue-100 dark:bg-primary-500/20 flex items-center justify-center flex-shrink-0">
      <span className="text-blue-700 dark:text-blue-400 text-xs font-bold">{initials}</span>
    </div>
  );
}

function StatusBadge({ status }) {
  const active = status === 'ACTIVO';
  return (
    <span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${
      active ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
              : 'bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400'
    }`}>
      <span className={`w-1.5 h-1.5 rounded-full ${active ? 'bg-green-500' : 'bg-red-400'}`} />
      {status}
    </span>
  );
}

// ─── Modal ────────────────────────────────────────────────────────────────────
function UserModal({ user, onClose, onSave }) {
  const isNew = !user.id;
  const [form, setForm] = useState(() => ({
    name:     user.name     ?? '',
    email:    user.email    ?? '',
    role:     user.role     ?? 'INGENIERO',
    projects: user.projects ?? [],
    status:   user.status   ?? 'ACTIVO',
  }));

  const set = (field, val) => setForm(f => ({ ...f, [field]: val }));

  const toggleProject = (p) => {
    setForm(f => {
      const list = f.projects.includes(p)
        ? f.projects.filter(x => x !== p)
        : [...f.projects, p];
      return { ...f, projects: list };
    });
  };

  const toggleAll = () => {
    setForm(f => ({
      ...f,
      projects: f.projects.includes('all') ? [] : ['all'],
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!form.name.trim() || !form.email.trim()) return;
    onSave({ ...user, ...form, id: user.id ?? `u${Date.now()}`, avatar: form.name.split(' ').map(w=>w[0]).join('').toUpperCase().slice(0,2) });
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-white dark:bg-surface-800 rounded-2xl shadow-xl w-full max-w-lg mx-4 p-6" onClick={e=>e.stopPropagation()}>
        <div className="flex items-center justify-between mb-5">
          <h2 className="text-lg font-semibold text-slate-900 dark:text-white">
            {isNew ? 'Nuevo usuario' : 'Editar usuario'}
          </h2>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-gray-200 transition-colors cursor-pointer">
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/>
            </svg>
          </button>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Nombre */}
          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-gray-300 mb-1">Nombre completo</label>
            <input
              value={form.name}
              onChange={e=>set('name',e.target.value)}
              required
              placeholder="Nombre Apellido"
              className="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* Email */}
          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-gray-300 mb-1">Email</label>
            <input
              type="email"
              value={form.email}
              onChange={e=>set('email',e.target.value)}
              required
              placeholder="usuario@empresa.com"
              className="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* Rol */}
          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-gray-300 mb-1">Rol</label>
            <select
              value={form.role}
              onChange={e=>set('role',e.target.value)}
              className="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              {ROLE_ORDER.map(r => (
                <option key={r} value={r}>{ROLE_LABELS[r]}</option>
              ))}
            </select>
          </div>

          {/* Proyectos */}
          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-gray-300 mb-2">Proyectos asignados</label>
            <div className="flex flex-wrap gap-2">
              <label className="flex items-center gap-1.5 cursor-pointer">
                <input type="checkbox" checked={form.projects.includes('all')} onChange={toggleAll} className="rounded border-slate-300 text-blue-600"/>
                <span className="text-sm text-slate-700 dark:text-gray-300">Todos los proyectos</span>
              </label>
              {MOCK_PROJECTS.map(p => (
                <label key={p.code} className={`flex items-center gap-1.5 cursor-pointer ${form.projects.includes('all') ? 'opacity-40' : ''}`}>
                  <input
                    type="checkbox"
                    checked={form.projects.includes(p.code)}
                    onChange={() => !form.projects.includes('all') && toggleProject(p.code)}
                    disabled={form.projects.includes('all')}
                    className="rounded border-slate-300 text-blue-600"
                  />
                  <span className="text-sm text-slate-700 dark:text-gray-300">
                    <span className="font-mono text-xs text-slate-400 dark:text-gray-500 mr-1">{p.code}</span>
                    {p.name}
                  </span>
                </label>
              ))}
            </div>
          </div>

          {/* Estado */}
          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-gray-300 mb-1">Estado</label>
            <div className="flex gap-4">
              {['ACTIVO','INACTIVO'].map(s => (
                <label key={s} className="flex items-center gap-2 cursor-pointer">
                  <input type="radio" name="status" value={s} checked={form.status===s} onChange={()=>set('status',s)} className="text-blue-600"/>
                  <span className="text-sm text-slate-700 dark:text-gray-300">{s}</span>
                </label>
              ))}
            </div>
          </div>

          {/* Actions */}
          <div className="flex gap-3 pt-2">
            <button type="button" onClick={onClose}
              className="flex-1 px-4 py-2 rounded-lg border border-slate-200 dark:border-surface-600 text-slate-700 dark:text-gray-300 text-sm font-medium hover:bg-slate-50 dark:hover:bg-surface-700 transition-colors cursor-pointer">
              Cancelar
            </button>
            <button type="submit"
              className="flex-1 px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors cursor-pointer">
              {isNew ? 'Crear usuario' : 'Guardar cambios'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ─── Tab: Usuarios ────────────────────────────────────────────────────────────
function UsersTab({ users, onNew, onEdit, onToggleStatus }) {
  const [confirmId, setConfirmId] = useState(null);

  const handleToggle = (u) => {
    if (u.status === 'ACTIVO') {
      setConfirmId(u.id);
    } else {
      onToggleStatus(u.id);
    }
  };

  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b border-slate-200 dark:border-surface-700">
            <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">Usuario</th>
            <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">Email</th>
            <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">Rol</th>
            <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">Proyectos</th>
            <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">Estado</th>
            <th className="text-right px-4 py-3 text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">Acciones</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-slate-100 dark:divide-surface-700">
          {users.map(u => (
            <tr key={u.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/50 transition-colors">
              {/* Avatar + Nombre */}
              <td className="px-4 py-3">
                <div className="flex items-center gap-3">
                  <Avatar initials={u.avatar} />
                  <span className="font-medium text-slate-900 dark:text-white">{u.name}</span>
                </div>
              </td>
              {/* Email */}
              <td className="px-4 py-3 text-slate-500 dark:text-gray-400">{u.email}</td>
              {/* Rol */}
              <td className="px-4 py-3"><RoleBadge role={u.role} /></td>
              {/* Proyectos */}
              <td className="px-4 py-3">
                {u.projects.includes('all')
                  ? <span className="text-slate-400 dark:text-gray-500 italic text-xs">Todos</span>
                  : <div className="flex flex-wrap gap-1">
                      {u.projects.map(p => (
                        <span key={p} className="inline-block px-1.5 py-0.5 rounded bg-slate-100 dark:bg-surface-600 text-slate-600 dark:text-gray-300 text-xs">{p}</span>
                      ))}
                    </div>
                }
              </td>
              {/* Estado */}
              <td className="px-4 py-3"><StatusBadge status={u.status} /></td>
              {/* Acciones */}
              <td className="px-4 py-3">
                <div className="flex items-center justify-end gap-2">
                  <button
                    onClick={() => onEdit(u)}
                    className="px-3 py-1.5 rounded-lg text-xs font-medium text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors cursor-pointer border border-blue-200 dark:border-blue-800">
                    Editar
                  </button>

                  {confirmId === u.id ? (
                    <div className="flex items-center gap-1.5">
                      <span className="text-xs text-slate-500 dark:text-gray-400">¿Desactivar?</span>
                      <button
                        onClick={() => { onToggleStatus(u.id); setConfirmId(null); }}
                        className="px-2 py-1 rounded text-xs font-medium bg-red-600 text-white hover:bg-red-700 transition-colors cursor-pointer">
                        Sí
                      </button>
                      <button
                        onClick={() => setConfirmId(null)}
                        className="px-2 py-1 rounded text-xs font-medium border border-slate-200 dark:border-surface-600 text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-surface-700 transition-colors cursor-pointer">
                        No
                      </button>
                    </div>
                  ) : (
                    <button
                      onClick={() => handleToggle(u)}
                      className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors cursor-pointer border ${
                        u.status === 'ACTIVO'
                          ? 'text-red-600 dark:text-red-400 border-red-200 dark:border-red-800 hover:bg-red-50 dark:hover:bg-red-900/20'
                          : 'text-green-600 dark:text-green-400 border-green-200 dark:border-green-800 hover:bg-green-50 dark:hover:bg-green-900/20'
                      }`}>
                      {u.status === 'ACTIVO' ? 'Desactivar' : 'Activar'}
                    </button>
                  )}
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ─── Tab: Matriz de permisos ──────────────────────────────────────────────────
function MatrixTab() {
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm border-collapse">
        <thead>
          <tr className="border-b border-slate-200 dark:border-surface-700">
            <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider min-w-[180px]">Módulo</th>
            {ROLE_ORDER.map(r => (
              <th key={r} className="px-3 py-3 text-center">
                <span className={`inline-block px-2 py-0.5 rounded-full text-xs font-semibold ${ROLE_STYLES[r]}`}>
                  {r === 'FINANCIERO' ? 'FIN' : r === 'SUPERVISOR' ? 'SUP' : r === 'INGENIERO' ? 'ING' : r === 'CONTADOR' ? 'CONT' : r === 'GERENTE' ? 'GER' : r}
                </span>
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {PERM_GROUPS.map(({ group, items }) => (
            <React.Fragment key={group}>
              <tr>
                <td colSpan={ROLE_ORDER.length + 1} className="px-4 py-2 bg-slate-50 dark:bg-surface-700/50">
                  <span className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-widest">{group}</span>
                </td>
              </tr>
              {items.map(({ key, label }) => (
                <tr key={key} className="border-b border-slate-100 dark:border-surface-700/50 hover:bg-slate-50 dark:hover:bg-surface-700/30 transition-colors">
                  <td className="px-4 py-2.5 text-slate-700 dark:text-gray-300">{label}</td>
                  {ROLE_ORDER.map(r => {
                    const hasAccess = (PERMS[key] ?? []).includes(r);
                    return (
                      <td key={r} className="px-3 py-2.5 text-center">
                        {hasAccess ? (
                          <span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400 text-xs font-bold">✓</span>
                        ) : (
                          <span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-slate-100 dark:bg-surface-600 text-slate-300 dark:text-gray-600 text-xs">—</span>
                        )}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </React.Fragment>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ─── Main component ───────────────────────────────────────────────────────────
export default function UsersPage() {
  const [users, setUsers] = useState(MOCK_USERS_INITIAL);
  const [activeTab, setActiveTab] = useState('users');
  const [modal, setModal] = useState(null); // null | { mode: 'new'|'edit', user }

  const openNew  = () => setModal({ mode: 'new',  user: { ...EMPTY_FORM } });
  const openEdit = (u) => setModal({ mode: 'edit', user: u });
  const closeModal = () => setModal(null);

  const handleSave = (saved) => {
    setUsers(prev =>
      prev.some(u => u.id === saved.id)
        ? prev.map(u => u.id === saved.id ? saved : u)
        : [...prev, saved]
    );
    closeModal();
  };

  const handleToggleStatus = (id) => {
    setUsers(prev => prev.map(u =>
      u.id === id ? { ...u, status: u.status === 'ACTIVO' ? 'INACTIVO' : 'ACTIVO' } : u
    ));
  };

  const activeCount   = users.filter(u => u.status === 'ACTIVO').length;
  const inactiveCount = users.filter(u => u.status === 'INACTIVO').length;

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Usuarios y Roles</h1>
          <p className="text-slate-500 dark:text-gray-400 text-sm mt-0.5">
            Gestión de accesos y permisos del sistema
          </p>
        </div>
        <button
          onClick={openNew}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-xl transition-colors cursor-pointer shadow-sm">
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4"/>
          </svg>
          Nuevo usuario
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-3 gap-4">
        {[
          { label: 'Total usuarios', value: users.length, color: 'text-slate-900 dark:text-white' },
          { label: 'Activos',        value: activeCount,   color: 'text-green-600 dark:text-green-400' },
          { label: 'Inactivos',      value: inactiveCount, color: 'text-red-500 dark:text-red-400' },
        ].map(({ label, value, color }) => (
          <div key={label} className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 px-5 py-4">
            <p className="text-xs text-slate-500 dark:text-gray-400 font-medium uppercase tracking-wider">{label}</p>
            <p className={`text-2xl font-bold mt-1 ${color}`}>{value}</p>
          </div>
        ))}
      </div>

      {/* Card con tabs */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 overflow-hidden">
        {/* Tabs */}
        <div className="flex border-b border-slate-200 dark:border-surface-700 px-4">
          {[
            { id: 'users',  label: 'Usuarios' },
            { id: 'matrix', label: 'Matriz de permisos' },
          ].map(({ id, label }) => (
            <button
              key={id}
              onClick={() => setActiveTab(id)}
              className={`px-4 py-3.5 text-sm font-medium border-b-2 transition-colors cursor-pointer -mb-px ${
                activeTab === id
                  ? 'border-blue-600 text-blue-600 dark:text-blue-400 dark:border-blue-400'
                  : 'border-transparent text-slate-500 dark:text-gray-400 hover:text-slate-700 dark:hover:text-gray-200'
              }`}>
              {label}
            </button>
          ))}
        </div>

        {/* Content */}
        <div className="py-2">
          {activeTab === 'users'
            ? <UsersTab users={users} onNew={openNew} onEdit={openEdit} onToggleStatus={handleToggleStatus} />
            : <MatrixTab />
          }
        </div>
      </div>

      {/* Modal */}
      {modal && (
        <UserModal
          user={modal.user}
          onClose={closeModal}
          onSave={handleSave}
        />
      )}
    </div>
  );
}
