import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  UserPlus, 
  MoreVertical, 
  ShieldCheck, 
  Users,
  ChevronRight,
  AlertCircle,
  Radio,
  X,
  Check,
  ShieldAlert,
  Clock,
  MapPin,
  Edit2,
  LayoutDashboard} from 'lucide-react';
import { Card } from '../components/Common';
import { motion, AnimatePresence } from 'framer-motion';

import { authApi } from '../api/auth';
import './UserManagement.css';

type ManagementTab = 'RBAC_IDENTITY' | 'CCE_MANAGEMENT' | 'SECURITY_POLICIES';

export const UserManagement: React.FC = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState<ManagementTab>('RBAC_IDENTITY');
  const [showModal, setShowModal] = useState(false);
  const [editingUser, setEditingUser] = useState<any | null>(null);
  const [realUsers, setRealUsers] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [hospitalIdFilter, setHospitalIdFilter] = useState('');
  const [rolesList, setRolesList] = useState<any[]>([]);

  const loadRoles = async () => {
    try {
      const token = localStorage.getItem('teleems_token') || '';
      if (!token) return;
      const res = await authApi.getRoles(token);
      if (res.data && res.data.data) {
        setRolesList(res.data.data);
      }
    } catch (err) {
      console.error('Failed to fetch roles:', err);
    }
  };

  const loadUsers = async () => {
    try {
      const authStr = localStorage.getItem('teleems_auth');
      const token = localStorage.getItem('teleems_token') || '';
      if (!token) return;
      
      const response = await authApi.getUsers(token);

      if (response.status === 401 || response.message?.toLowerCase().includes('expired')) {
        localStorage.removeItem('teleems_auth');
        localStorage.removeItem('teleems_token');
        localStorage.removeItem('teleems_user');
        navigate('/login');
        return;
      }

      if (response && Array.isArray(response.data)) {
        const mapped = response.data.map((u: any) => ({
          id: u.id,
          name: u.name || u.username,
          phone: u.phone,
          role: (Array.isArray(u.roles) && u.roles.length > 0) ? u.roles[0] : 'N/A', 
          org: u.metadata?.organization?.company_name || u.metadata?.hospital?.name || u.metadata?.zone || 'TeleEMS Network',
          status: u.status || 'INACTIVE',
          mfa: !!u.mfaEnabled,
          hospitalId: u.hospitalId || u.organisationId || 'N/A',
          email: u.email || '',
          rawMetadata: u.metadata || {}
        }));
        setRealUsers(mapped);
      }
    } catch (error) {
      console.error('Failed to fetch users:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadUsers();
    loadRoles();
  }, []);

  const handleStatusToggle = async (user: any) => {
    try {
      const newStatus = user.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE';
      const token = localStorage.getItem('teleems_token') || '';
      
      const payload = {
        name: user.name,
        email: user.email,
        phone: user.phone || '',
        status: newStatus,
        role: user.role,
        metadata: user.rawMetadata
      };

      const res = await authApi.updateUser(user.id, payload, token);
      if (res.status === 401) {
        navigate('/login');
        return;
      }

      loadUsers();
    } catch (error) {
      console.error('Failed to toggle status:', error);
    }
  };

  const handleEditSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingUser) return;
    
    try {
      const token = localStorage.getItem('teleems_token') || '';
      const payload = {
        name: editingUser.name,
        email: editingUser.email,
        phone: editingUser.phone || '',
        status: editingUser.status,
        role: editingUser.role,
        metadata: editingUser.rawMetadata
      };

      const res = await authApi.updateUser(editingUser.id, payload, token);
      if (res.status === 401) {
        navigate('/login');
        return;
      }

      setEditingUser(null);
      loadUsers();
    } catch (error) {
       console.error('Update failed:', error);
    }
  };

  const [newUser, setNewUser] = useState({ name: '', role: 'FLEET_OPERATOR', org: '' });

  const handleAddUser = (e: React.FormEvent) => {
    e.preventDefault();
    const id = `user-${Math.floor(Math.random() * 1000)}`;
    setRealUsers([...realUsers, { ...newUser, id, status: 'ACTIVE', mfa: false, hospitalId: 'PENDING' }]);
    setShowModal(false);
    setNewUser({ name: '', role: 'FLEET_OPERATOR', org: '' });
  };

  const stats = useMemo(() => {
    const total = realUsers.length;
    const active = realUsers.filter(u => u.status === 'ACTIVE').length;
    const mfa = realUsers.filter(u => u.mfa).length;
    const admins = realUsers.filter(u => u.role?.includes('ADMIN')).length;
    return { total, active, mfa, admins };
  }, [realUsers]);

  const getInitials = (name: string) => {
    return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2);
  };

  return (
    <div className="page-container user-mgmt-container" style={{ display: 'flex', flexDirection: 'column', gap: '32px' }}>
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <h2 style={{ fontSize: '2.8rem', fontWeight: 900, background: 'linear-gradient(135deg, var(--text-primary) 0%, var(--accent-cyan) 100%)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', letterSpacing: '-0.03em' }}>
            Identity Hub
          </h2>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginTop: '6px' }}>
             <div className="pulse-active"></div>
             <p style={{ color: 'var(--text-secondary)', fontSize: '0.9rem', fontWeight: 500 }}>
                Enterprise RBAC & Security Command Center
             </p>
          </div>
        </div>
        
        <div className="glass" style={{ padding: '6px', borderRadius: '14px', display: 'flex', gap: '6px', background: 'rgba(0,0,0,0.02)', border: '1px solid rgba(0,0,0,0.05)' }}>
           {[
             { id: 'RBAC_IDENTITY', icon: Users, label: 'IDENTITIES' },
             { id: 'CCE_MANAGEMENT', icon: Radio, label: 'CCE NODES' },
             { id: 'SECURITY_POLICIES', icon: ShieldCheck, label: 'POLICIES' }
           ].map(tab => (
            <button 
              key={tab.id}
              onClick={() => setActiveTab(tab.id as any)}
              style={{ 
                padding: '10px 18px', borderRadius: '10px', border: 'none', 
                background: activeTab === tab.id ? 'var(--accent-cyan)' : 'transparent',
                color: activeTab === tab.id ? '#fff' : 'var(--text-secondary)',
                fontWeight: 800, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px', fontSize: '0.75rem',
                transition: 'all 0.3s ease',
                textTransform: 'uppercase',
                letterSpacing: '0.05em'
              }}>
              <tab.icon size={16} /> {tab.label}
            </button>
           ))}
        </div>
      </header>

      {/* STATS OVERVIEW */}
      <div className="stats-grid">
         <div className="stat-card-premium">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
               <div>
                  <div style={{ fontSize: '0.75rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Total Identities</div>
                  <div style={{ fontSize: '2.4rem', fontWeight: 900, color: 'var(--text-primary)', marginTop: '4px' }}>{stats.total}</div>
               </div>
               <Users size={24} color="var(--accent-cyan)" />
            </div>
            <div style={{ marginTop: '12px', fontSize: '0.75rem', color: 'var(--accent-green)', fontWeight: 700 }}>↑ 12% from last month</div>
         </div>
         <div className="stat-card-premium">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
               <div>
                  <div style={{ fontSize: '0.75rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Active Nodes</div>
                  <div style={{ fontSize: '2.4rem', fontWeight: 900, color: 'var(--text-primary)', marginTop: '4px' }}>{stats.active}</div>
               </div>
               <Radio size={24} color="var(--accent-green)" />
            </div>
            <div style={{ marginTop: '12px', fontSize: '0.75rem', color: 'var(--text-secondary)' }}>System availability: 100%</div>
         </div>
         <div className="stat-card-premium">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
               <div>
                  <div style={{ fontSize: '0.75rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>MFA Adoption</div>
                  <div style={{ fontSize: '2.4rem', fontWeight: 900, color: 'var(--text-primary)', marginTop: '4px' }}>{Math.round((stats.mfa/stats.total || 0) * 100)}%</div>
               </div>
               <ShieldCheck size={24} color="var(--accent-cyan)" />
            </div>
            <div style={{ marginTop: '12px', display: 'flex', gap: '4px' }}>
               {[1,2,3,4,5,6].map(i => <div key={i} style={{ flex: 1, height: '4px', borderRadius: '2px', background: i <= 5 ? 'var(--accent-cyan)' : 'rgba(0,0,0,0.03)' }}></div>)}
            </div>
         </div>
         <div className="stat-card-premium">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
               <div>
                  <div style={{ fontSize: '0.75rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Admin Control</div>
                  <div style={{ fontSize: '2.4rem', fontWeight: 900, color: 'var(--text-primary)', marginTop: '4px' }}>{stats.admins}</div>
               </div>
               <ShieldAlert size={24} color="var(--warning-amber)" />
            </div>
            <div style={{ marginTop: '12px', fontSize: '0.75rem', color: 'var(--warning-amber)', fontWeight: 700 }}>Privileged Access Level</div>
         </div>
      </div>

      {/* NEW USER MODAL (Existing logic) */}
      <AnimatePresence>
        {showModal && (
          <motion.div 
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            style={{ position: 'fixed', inset: 0, background: 'rgba(255,255,255,0.85)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px', backdropFilter: 'blur(8px)' }}>
            <motion.div 
              initial={{ scale: 0.9, y: 20 }} animate={{ scale: 1, y: 0 }} exit={{ scale: 0.9, y: 20 }}
              className="glass glow-cyan" style={{ width: '100%', maxWidth: '500px', padding: '40px', position: 'relative', border: '1px solid rgba(59,130,246,0.2)' }}>
              <button 
                 onClick={() => setShowModal(false)}
                 style={{ position: 'absolute', right: '24px', top: '24px', background: 'transparent', border: 'none', color: 'var(--text-secondary)', cursor: 'pointer' }}>
                 <X size={24} />
              </button>
              <h3 style={{ fontSize: '1.5rem', marginBottom: '8px', fontWeight: 800 }}>Provision New Identity</h3>
              <p style={{ fontSize: '0.85rem', color: 'var(--text-secondary)', marginBottom: '32px' }}>Assign roles and organizational hierarchy to a new platform user.</p>
              
              <form onSubmit={handleAddUser} style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
                 <div>
                    <label style={{ display: 'block', fontSize: '0.7rem', color: 'var(--accent-cyan)', marginBottom: '10px', fontWeight: 700, textTransform: 'uppercase' }}>Full Legal Name</label>
                    <input 
                      type="text" required value={newUser.name}
                      onChange={(e) => setNewUser({...newUser, name: e.target.value})}
                      style={{ width: '100%', padding: '14px', background: 'rgba(0,0,0,0.02)', border: '1px solid var(--card-border)', borderRadius: '8px', color: 'var(--text-primary)' }} 
                    />
                 </div>
                 <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '20px' }}>
                    <div>
                        <label style={{ display: 'block', fontSize: '0.7rem', color: 'var(--accent-cyan)', marginBottom: '10px', fontWeight: 700, textTransform: 'uppercase' }}>Role Assignment</label>
                        <select 
                          value={newUser.role}
                          onChange={(e) => setNewUser({...newUser, role: e.target.value})}
                          style={{ width: '100%', padding: '14px', background: 'rgba(0,0,0,0.03)', border: '1px solid var(--card-border)', borderRadius: '8px', color: 'var(--text-primary)' }}
                        >
                           {rolesList.map((r: any) => (
                              <option key={r.id} value={r.name}>{r.name}</option>
                           ))}
                        </select>
                    </div>
                    <div>
                        <label style={{ display: 'block', fontSize: '0.7rem', color: 'var(--accent-cyan)', marginBottom: '10px', fontWeight: 700, textTransform: 'uppercase' }}>Organisation</label>
                        <input 
                          type="text" required value={newUser.org}
                          onChange={(e) => setNewUser({...newUser, org: e.target.value})}
                          style={{ width: '100%', padding: '14px', background: 'rgba(0,0,0,0.02)', border: '1px solid var(--card-border)', borderRadius: '8px', color: 'var(--text-primary)' }} 
                        />
                    </div>
                 </div>
                 <button type="submit" style={{ width: '100%', padding: '16px', background: 'var(--accent-cyan)', border: 'none', borderRadius: '8px', fontWeight: 800, color: '#fff', cursor: 'pointer', marginTop: '10px', boxShadow: '0 8px 20px rgba(59,130,246,0.3)' }}>
                    GENERATE SECURE CREDENTIALS
                 </button>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* EDIT USER MODAL */}
      <AnimatePresence>
        {editingUser && (
          <motion.div 
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            style={{ position: 'fixed', inset: 0, background: 'rgba(255,255,255,0.85)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px', backdropFilter: 'blur(8px)' }}>
            <motion.div 
              initial={{ scale: 0.9, y: 20 }} animate={{ scale: 1, y: 0 }} exit={{ scale: 0.9, y: 20 }}
              className="glass glow-amber" style={{ width: '100%', maxWidth: '500px', padding: '40px', position: 'relative', border: '1px solid rgba(255,191,0,0.3)' }}>
              <button 
                 onClick={() => setEditingUser(null)}
                 style={{ position: 'absolute', right: '24px', top: '24px', background: 'transparent', border: 'none', color: 'var(--text-secondary)', cursor: 'pointer' }}>
                 <X size={24} />
              </button>
              <h3 style={{ fontSize: '1.5rem', marginBottom: '8px', fontWeight: 800 }}>Edit Identity Profile</h3>
              <p style={{ fontSize: '0.85rem', color: 'var(--text-secondary)', marginBottom: '32px' }}>Update platform access, organizational ties, and metadata nodes.</p>
              
              <form onSubmit={handleEditSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
                 <div>
                    <label style={{ display: 'block', fontSize: '0.7rem', color: 'var(--warning-amber)', marginBottom: '10px', fontWeight: 700, textTransform: 'uppercase' }}>Full Display Name</label>
                    <input 
                      type="text" required value={editingUser.name}
                      onChange={(e) => setEditingUser({...editingUser, name: e.target.value})}
                      style={{ width: '100%', padding: '14px', background: 'rgba(0,0,0,0.02)', border: '1px solid var(--card-border)', borderRadius: '8px', color: 'var(--text-primary)' }} 
                    />
                 </div>
                 <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
                    <div>
                        <label style={{ display: 'block', fontSize: '0.7rem', color: 'var(--warning-amber)', marginBottom: '10px', fontWeight: 700, textTransform: 'uppercase' }}>Email Address</label>
                        <input 
                          type="email" required value={editingUser.email}
                          onChange={(e) => setEditingUser({...editingUser, email: e.target.value})}
                          style={{ width: '100%', padding: '14px', background: 'rgba(0,0,0,0.02)', border: '1px solid var(--card-border)', borderRadius: '8px', color: 'var(--text-primary)' }} 
                        />
                    </div>
                    <div>
                        <label style={{ display: 'block', fontSize: '0.7rem', color: 'var(--warning-amber)', marginBottom: '10px', fontWeight: 700, textTransform: 'uppercase' }}>Phone Contact</label>
                        <input 
                          type="text" value={editingUser.phone || ''}
                          onChange={(e) => setEditingUser({...editingUser, phone: e.target.value})}
                          style={{ width: '100%', padding: '14px', background: 'rgba(0,0,0,0.02)', border: '1px solid var(--card-border)', borderRadius: '8px', color: 'var(--text-primary)' }} 
                        />
                    </div>
                 </div>
                 <div>
                    <label style={{ display: 'block', fontSize: '0.7rem', color: 'var(--warning-amber)', marginBottom: '10px', fontWeight: 700, textTransform: 'uppercase' }}>Role Assignment</label>
                    <select 
                      value={editingUser.role}
                      onChange={(e) => setEditingUser({...editingUser, role: e.target.value})}
                      style={{ width: '100%', padding: '14px', background: 'rgba(0,0,0,0.03)', border: '1px solid var(--card-border)', borderRadius: '8px', color: 'var(--text-primary)' }}
                    >
                       {rolesList.map((r: any) => (
                          <option key={r.id} value={r.name}>{r.name}</option>
                       ))}
                    </select>
                 </div>
                 <button type="submit" style={{ width: '100%', padding: '16px', background: 'var(--warning-amber)', border: 'none', borderRadius: '8px', fontWeight: 800, color: '#fff', cursor: 'pointer', marginTop: '10px' }}>
                    PERSIST IDENTITY CHANGES
                 </button>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <AnimatePresence mode="wait">
         {activeTab === 'RBAC_IDENTITY' && (
           <motion.div key="rbac" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }} style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '32px' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '32px' }}>
                 <Card title="Active Platform Users" subtitle="Manage credentials and multi-factor authentication status.">
                    <div style={{ display: 'flex', gap: '20px', marginBottom: '20px', padding: '0 16px' }}>
                       <div style={{ flex: 1 }}>
                          <label style={{ display: 'block', fontSize: '0.65rem', color: 'var(--accent-cyan)', marginBottom: '8px', fontWeight: 800 }}>SEARCH IDENTITY</label>
                          <input 
                            type="text" 
                            placeholder="Search name or email..." 
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            style={{ width: '100%', padding: '10px', background: 'rgba(0,0,0,0.02)', border: '1px solid var(--card-border)', borderRadius: '6px', color: 'var(--text-primary)', fontSize: '0.8rem' }}
                          />
                       </div>
                       <div style={{ width: '300px' }}>
                          <label style={{ display: 'block', fontSize: '0.65rem', color: 'var(--accent-cyan)', marginBottom: '8px', fontWeight: 800 }}>FILTER BY HOSPITAL / ORG ID</label>
                          <input 
                            type="text" 
                            placeholder="Enter Hospital ID..." 
                            value={hospitalIdFilter}
                            onChange={(e) => setHospitalIdFilter(e.target.value)}
                            style={{ width: '100%', padding: '10px', background: 'rgba(0,0,0,0.02)', border: '1px solid var(--card-border)', borderRadius: '6px', color: 'var(--text-primary)', fontSize: '0.8rem', fontFamily: 'monospace' }}
                          />
                       </div>
                    </div>
                    <div className="table-scroll-container" style={{ overflowX: 'auto', padding: '0 16px' }}>
                       <table className="identity-table-premium">
                         <thead>
                           <tr>
                             <th>User Identity</th>
                             <th>Hospital / Org ID</th>
                             <th>Role Node</th>
                             <th>Contact</th>
                             <th>Status & MFA</th>
                             <th style={{ textAlign: 'right' }}>Actions</th>
                           </tr>
                         </thead>
                         <tbody>
                           {realUsers
                             .filter(user => {
                               const matchesSearch = (user.name || '').toLowerCase().includes(searchTerm.toLowerCase()) || 
                                                   (user.email || '').toLowerCase().includes(searchTerm.toLowerCase());
                               const matchesHospId = !hospitalIdFilter || String(user.hospitalId).includes(hospitalIdFilter);
                               return matchesSearch && matchesHospId;
                             })
                             .map((user) => (
                             <tr key={user.id} className="identity-row">
                               <td>
                                  <div className="user-identity-cell">
                                     <div className="avatar-initials">{getInitials(user.name)}</div>
                                     <div>
                                        <div style={{ fontWeight: 800, fontSize: '0.95rem', color: 'var(--text-primary)' }}>{user.name}</div>
                                        <div className="mono" style={{ fontSize: '0.65rem', color: 'var(--text-secondary)', marginTop: '2px' }}>{user.org}</div>
                                     </div>
                                  </div>
                               </td>
                               <td>
                                 <div className="mono" style={{ fontSize: '0.75rem', color: 'var(--accent-cyan)', fontWeight: 800, background: 'rgba(59,130,246,0.05)', padding: '4px 8px', borderRadius: '4px', display: 'inline-block' }}>{user.hospitalId}</div>
                               </td>
                               <td>
                                  <span className={`role-badge ${user.role?.includes('ADMIN') ? 'role-super' : user.role?.includes('CCE') ? 'role-cce' : 'role-admin'}`}>
                                     {user.role}
                                  </span>
                               </td>
                               <td>
                                  <div style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', fontWeight: 500 }}>{user.phone || 'N/A'}</div>
                                  <div style={{ fontSize: '0.65rem', color: 'var(--text-secondary)', opacity: 0.6, marginTop: '2px' }}>{user.email}</div>
                               </td>
                               <td>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                     <div className={user.status === 'ACTIVE' ? 'pulse-active' : ''} style={{ background: user.status === 'ACTIVE' ? 'var(--accent-green)' : 'var(--warning-amber)' }}></div>
                                     <span style={{ fontWeight: 700, fontSize: '0.75rem', letterSpacing: '0.05em' }}>{user.status}</span>
                                     {user.mfa && <ShieldCheck size={14} color="var(--accent-green)" />}
                                  </div>
                               </td>
                               <td style={{ textAlign: 'right' }}>
                                  <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
                                     <button 
                                        onClick={() => setEditingUser(user)}
                                        className="btn-icon"
                                        style={{ color: 'var(--accent-cyan)' }}>
                                        <Edit2 size={16} />
                                      </button>
                                     <button 
                                       onClick={() => handleStatusToggle(user)}
                                       style={{ 
                                         padding: '6px 14px', background: user.status === 'ACTIVE' ? 'rgba(255, 59, 59, 0.1)' : 'rgba(0, 255, 136, 0.1)', 
                                         border: `1px solid ${user.status === 'ACTIVE' ? 'rgba(255, 59, 59, 0.2)' : 'rgba(0, 255, 136, 0.2)'}`, 
                                         borderRadius: '6px', fontSize: '0.65rem', color: user.status === 'ACTIVE' ? 'var(--alert-red)' : 'var(--accent-green)', 
                                         fontWeight: 900, cursor: 'pointer', letterSpacing: '0.05em'
                                       }}>
                                       {user.status === 'ACTIVE' ? 'REVOKE' : 'RECOVER'}
                                     </button>
                                  </div>
                                </td>
                             </tr>
                           ))}
                         </tbody>
                       </table>
                    </div>
                    <div style={{ marginTop: '24px', display: 'flex', justifyContent: 'center' }}>
                       <button onClick={() => setShowModal(true)} style={{ padding: '12px 24px', background: 'var(--accent-cyan)', border: 'none', borderRadius: '8px', fontWeight: 800, color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px' }}>
                          <UserPlus size={18} /> PROVISION NEW IDENTITY
                       </button>
                    </div>
                 </Card>

                 <Card title="Permissions Inheritance Matrix">
                    <div style={{ overflowX: 'auto' }}>
                      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.75rem' }}>
                        <thead>
                          <tr style={{ background: 'rgba(0,0,0,0.02)' }}>
                             <th style={{ padding: '12px', textAlign: 'left' }}>Global Permission Node</th>
                             <th style={{ padding: '12px' }}>Super_Admin</th>
                             <th style={{ padding: '12px' }}>Hosp_Admin</th>
                             <th style={{ padding: '12px' }}>Fleet_Ops</th>
                             <th style={{ padding: '12px' }}>CCE</th>
                          </tr>
                        </thead>
                        <tbody>
                           {[
                             { node: 'CORE_SYSTEM_WRITE', roles: [1, 0, 0, 0] },
                             { node: 'ENTITY_ONBOARD_MGMT', roles: [1, 0, 0, 0] },
                             { node: 'INCIDENT_COMMAND_IO', roles: [1, 1, 1, 1] },
                             { node: 'MEDICAL_RECORDS_READ', roles: [1, 1, 0, 1] },
                             { node: 'FLEET_ROUTING_CONTROL', roles: [1, 0, 1, 1] },
                             { node: 'FINANCIAL_AUDIT_VIEW', roles: [1, 0, 0, 0] },
                           ].map((row, i) => (
                             <tr key={i} style={{ borderBottom: '1px solid rgba(0,0,0,0.02)' }}>
                               <td style={{ padding: '12px', fontWeight: 700, color: 'var(--accent-cyan)' }}>{row.node}</td>
                               {row.roles.map((enabled, index) => (
                                 <td key={index} style={{ padding: '12px', textAlign: 'center' }}>
                                    {enabled ? <Check size={16} color="var(--accent-green)" style={{ margin: '0 auto' }} /> : <X size={16} color="rgba(0,0,0,0.05)" style={{ margin: '0 auto' }} />}
                                 </td>
                               ))}
                             </tr>
                           ))}
                         </tbody>
                       </table>
                    </div>
                 </Card>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: '32px' }}>
                 <Card title="Security Pulse">
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
                       <div style={{ background: 'rgba(255, 59, 59, 0.05)', border: '1px solid rgba(255, 59, 59, 0.2)', padding: '16px', borderRadius: '12px' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '10px', color: 'var(--alert-red)' }}>
                             <ShieldAlert size={18} />
                             <span style={{ fontWeight: 800, fontSize: '0.85rem' }}>Failed Login Spike</span>
                          </div>
                          <p style={{ fontSize: '0.75rem', color: 'var(--text-secondary)', marginTop: '8px' }}>Detected 42 failed attempts from IP 103.11.x.x in the last 10 minutes.</p>
                       </div>
                       
                       <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                             <span style={{ fontSize: '0.85rem' }}>Global MFA Level</span>
                             <span style={{ color: 'var(--accent-green)', fontWeight: 800, fontSize: '0.85rem' }}>92%</span>
                          </div>
                          <div style={{ width: '100%', height: '6px', background: 'rgba(0,0,0,0.05)', borderRadius: '3px' }}>
                             <div style={{ width: '92%', height: '100%', background: 'linear-gradient(90deg, var(--accent-cyan), var(--accent-green))', borderRadius: '3px' }}></div>
                          </div>
                       </div>
                    </div>
                 </Card>

                 <Card title="IP Whitelisting (Admin)">
                    <p style={{ fontSize: '0.75rem', color: 'var(--text-secondary)', marginBottom: '16px' }}>Restrict Super Admin access to specific corporate CIDRs.</p>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                       {['122.164.x.x (HQ Chennai)', '106.51.x.x (Secure VPN)'].map((ip, i) => (
                         <div key={i} style={{ padding: '8px 12px', background: 'rgba(0,0,0,0.03)', borderRadius: '6px', fontSize: '0.75rem', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <span className="mono">{ip}</span>
                            <X size={14} color="var(--text-secondary)" style={{ cursor: 'pointer' }} />
                         </div>
                       ))}
                       <button style={{ marginTop: '10px', padding: '8px', background: 'transparent', border: '1px dashed var(--card-border)', borderRadius: '6px', fontSize: '0.75rem', color: 'var(--text-secondary)', cursor: 'pointer' }}>+ ADD CIDR BLOCK</button>
                    </div>
                 </Card>
              </div>
           </motion.div>
         )}

         {activeTab === 'CCE_MANAGEMENT' && <CCEManagement key="cce" />}
         
         {activeTab === 'SECURITY_POLICIES' && (
           <motion.div key="security" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}>
              <Card title="Global Authentication Policy">
                 <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '32px' }}>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                       <div style={{ fontWeight: 800, fontSize: '0.9rem', color: 'var(--accent-cyan)' }}>Session Settings</div>
                       <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span style={{ fontSize: '0.85rem' }}>Idle Timeout</span>
                          <span className="mono" style={{ fontWeight: 700 }}>30 MINS</span>
                       </div>
                       <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span style={{ fontSize: '0.85rem' }}>Concurrent Logins</span>
                          <span className="mono" style={{ fontWeight: 700 }}>RESTRICTED</span>
                       </div>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                       <div style={{ fontWeight: 800, fontSize: '0.9rem', color: 'var(--accent-cyan)' }}>Password Policy</div>
                       <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span style={{ fontSize: '0.85rem' }}>Expiry Cycle</span>
                          <span className="mono" style={{ fontWeight: 700 }}>90 DAYS</span>
                       </div>
                       <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span style={{ fontSize: '0.85rem' }}>History Enforcement</span>
                          <span className="mono" style={{ fontWeight: 700 }}>5 RECENT</span>
                       </div>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                       <div style={{ fontWeight: 800, fontSize: '0.9rem', color: 'var(--accent-cyan)' }}>Account Lockout</div>
                       <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span style={{ fontSize: '0.85rem' }}>Max Failed Attempts</span>
                          <span className="mono" style={{ fontWeight: 700 }}>5 RETRIES</span>
                       </div>
                       <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span style={{ fontSize: '0.85rem' }}>Lock Duration</span>
                          <span className="mono" style={{ fontWeight: 700 }}>60 MINS</span>
                       </div>
                    </div>
                 </div>
              </Card>
           </motion.div>
         )}
      </AnimatePresence>
    </div>
  );
};

// 5.6 Call Centre Management
const CCEManagement = () => {
  const ccePools = [
    { id: 'POOL_01', name: 'Strategic Dispatch Pool (Chennai)', cces: 12, standby: 4, active: 8, zones: ['Chennai', 'Kanchipuram'], shift: 'SH1 (06:00-14:00)' },
    { id: 'POOL_02', name: 'Central Hub Pool (Coimbatore)', cces: 18, standby: 6, active: 10, zones: ['Coimbatore', 'Erode', 'Salem'], shift: 'SH1 (06:00-14:00)' },
    { id: 'POOL_03', name: 'South Zone Transit (Madurai)', cces: 8, standby: 2, active: 6, zones: ['Madurai', 'Trichy'], shift: 'SH2 (14:00-22:00)' },
  ];

  return (
    <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }} style={{ display: 'flex', flexDirection: 'column', gap: '32px' }}>
       <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '24px' }}>
          {ccePools.map((pool, i) => (
            <Card key={i} className="hover-glow">
               <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '16px' }}>
                  <div style={{ width: '40px', height: '40px', background: 'rgba(59, 130, 246, 0.1)', borderRadius: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                     <Radio size={20} color="var(--accent-cyan)" />
                  </div>
                  <div style={{ fontSize: '0.65rem', fontWeight: 800, color: 'var(--text-secondary)' }} className="mono">{pool.id}</div>
               </div>
               <div style={{ fontSize: '1.1rem', fontWeight: 800, marginBottom: '4px' }}>{pool.name}</div>
               <div style={{ fontSize: '0.75rem', color: 'var(--accent-cyan)', display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '16px' }}>
                  <Clock size={12} /> {pool.shift}
               </div>
               
               <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px', marginBottom: '20px' }}>
                  <div style={{ textAlign: 'center', background: 'rgba(0,0,0,0.03)', padding: '8px', borderRadius: '8px' }}>
                     <div style={{ fontSize: '1rem', fontWeight: 800 }}>{pool.cces}</div>
                     <div style={{ fontSize: '0.6rem', color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Total</div>
                  </div>
                  <div style={{ textAlign: 'center', background: 'rgba(0,255,136,0.05)', padding: '8px', borderRadius: '8px', border: '1px solid rgba(0,255,136,0.1)' }}>
                     <div style={{ fontSize: '1rem', fontWeight: 800, color: 'var(--accent-green)' }}>{pool.active}</div>
                     <div style={{ fontSize: '0.6rem', color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Online</div>
                  </div>
                  <div style={{ textAlign: 'center', background: 'rgba(255,184,0,0.05)', padding: '8px', borderRadius: '8px', border: '1px solid rgba(255,184,0,0.1)' }}>
                     <div style={{ fontSize: '1rem', fontWeight: 800, color: 'var(--warning-amber)' }}>{pool.standby}</div>
                     <div style={{ fontSize: '0.6rem', color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Idle</div>
                  </div>
               </div>

               <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px', borderTop: '1px solid var(--card-border)', paddingTop: '16px' }}>
                  {pool.zones.map(z => (
                    <span key={z} style={{ fontSize: '0.65rem', padding: '2px 8px', background: 'rgba(0,0,0,0.03)', borderRadius: '4px', color: 'var(--text-secondary)' }}>{z}</span>
                  ))}
                  <button style={{ marginLeft: 'auto', background: 'transparent', border: 'none', color: 'var(--accent-cyan)', cursor: 'pointer' }}><ChevronRight size={16} /></button>
               </div>
            </Card>
          ))}
       </div>

       <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '32px' }}>
          <Card title="Call Routing Configuration" subtitle="Geographic priority and load-based allocation.">
             <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                {[
                  { region: 'District Cluster A', strategy: 'Round Robin', priority: 'High', load: '65%' },
                  { region: 'Metropolitan Core', strategy: 'Skill-based (Language)', priority: 'Emergency', load: '82%' },
                  { region: 'Northern Highways', strategy: 'Geographic Proximity', priority: 'Standard', load: '30%' },
                ].map((row, i) => (
                  <div key={i} style={{ padding: '16px', background: 'rgba(0,0,0,0.01)', borderRadius: '12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', border: '1px solid var(--card-border)' }}>
                     <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                        <MapPin size={24} color="var(--accent-cyan)" />
                        <div>
                           <div style={{ fontWeight: 800, fontSize: '1rem' }}>{row.region}</div>
                           <div style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>Logic: {row.strategy}</div>
                        </div>
                     </div>
                     <div style={{ textAlign: 'right' }}>
                        <div style={{ fontWeight: 800, color: 'var(--accent-cyan)' }}>{row.priority}</div>
                        <div style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>LOAD: {row.load}</div>
                     </div>
                  </div>
                ))}
                <button style={{ padding: '14px', background: 'transparent', border: '1px dashed var(--card-border)', borderRadius: '12px', color: 'var(--text-secondary)', fontSize: '0.8rem', cursor: 'pointer', fontWeight: 600 }}>
                   + CONFIGURE NEW ROUTING DOMAIN
                </button>
             </div>
          </Card>

          <Card title="SLA & Escalation Timers">
             <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
                <div>
                   <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                      <span style={{ fontSize: '0.85rem' }}>Max Hold Time</span>
                      <span className="mono" style={{ fontWeight: 800, color: 'var(--accent-cyan)' }}>45s</span>
                   </div>
                   <div style={{ width: '100%', height: '4px', background: 'rgba(0,0,0,0.03)', borderRadius: '2px' }}>
                      <div style={{ width: '45%', height: '100%', background: 'var(--accent-cyan)', borderRadius: '2px' }}></div>
                   </div>
                </div>
                <div>
                   <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                      <span style={{ fontSize: '0.85rem' }}>Max Dispatch Delay</span>
                      <span className="mono" style={{ fontWeight: 800, color: 'var(--accent-cyan)' }}>120s</span>
                   </div>
                   <div style={{ width: '100%', height: '4px', background: 'rgba(0,0,0,0.03)', borderRadius: '2px' }}>
                      <div style={{ width: '70%', height: '100%', background: 'var(--accent-cyan)', borderRadius: '2px' }}></div>
                   </div>
                </div>
                
                <div style={{ background: 'rgba(59, 130, 246, 0.05)', padding: '16px', borderRadius: '12px', marginTop: '10px' }}>
                   <div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: 'var(--accent-cyan)', marginBottom: '8px' }}>
                      <AlertCircle size={16} />
                      <span style={{ fontWeight: 800, fontSize: '0.8rem' }}>Auto-Escalation Rule</span>
                   </div>
                   <p style={{ fontSize: '0.7rem', color: 'var(--text-secondary)', lineHeight: '1.4' }}>
                      If a critical incident is not acknowledged within 90s, notify Supervisor and Regional Ops Manager via SMS/Push.
                   </p>
                </div>
             </div>
          </Card>
       </div>
    </motion.div>
  );
};
