import React, { useState, useEffect, useMemo } from 'react';
import { 
  Settings as SettingsIcon, 
  User, 
  Shield, 
  Bell, 
  Globe, 
  Database, 
  Key, 
  Mail, 
  Save, 
  RefreshCcw, 
  Trash2, 
  Plus,
  ChevronRight,
  Monitor,
  Smartphone,
  Lock,
  MoreHorizontal,
  Check,
  Eye,
  Edit3,
  Trash,
  Phone,
  AlertCircle,
  TrendingUp,
  Briefcase,
  DollarSign,
  Users,
  Target,
  Building2,
  FileArchive
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Copy } from 'lucide-react';
import { DataManagement } from '@/components/Settings/DataManagement';
import { CodeImport } from '@/components/Settings/CodeImport';
import { storage } from '@/lib/storage';
import { useAuth } from '@/context/AuthContext';
import { useApp } from '@/context/AppContext';

export function Settings() {
  const { profile, rolePermissions, updateRolePermissions, modules, roles: authRoles, systemUsers: globalUsers, updateSystemUsers, updateRoles, hasPermission } = useAuth();
  const { companySettings, updateCompanySettings } = useApp();
  const [activeTab, setActiveTab] = useState<'general' | 'users' | 'security' | 'notifications' | 'integrations' | 'data' | 'import'>('general');
  const [userViewTab, setUserViewTab] = useState<'permissions' | 'assigned-users'>('permissions');
  const [selectedRole, setSelectedRole] = useState<string | null>('Administrator');
  const [isAddRoleModalOpen, setIsAddRoleModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<{ id: string; name: string } | null>(null);
  const [newRole, setNewRole] = useState({ name: '', description: '' });
  const [editingRole, setEditingRole] = useState<string | null>(null);
  const [activeRoleMenu, setActiveRoleMenu] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [isAddUserModalOpen, setIsAddUserModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<string | null>(null);
  const [companyName, setCompanyName] = useState(companySettings.name || '');
  const [companyEmail, setCompanyEmail] = useState(companySettings.email || '');
  const [companyLogo, setCompanyLogo] = useState(companySettings.logo || '');
  const [companyLocation, setCompanyLocation] = useState(companySettings.location || '');
  const [companyPhone, setCompanyPhone] = useState(companySettings.phone || '');
  const [userData, setUserData] = useState({
    fullName: '',
    email: '',
    password: '',
    phone: '',
    role: 'Employee'
  });

  const rolesCount = useMemo(() => {
    const counts: Record<string, number> = {};
    globalUsers.forEach((u: any) => {
      counts[u.role] = (counts[u.role] || 0) + 1;
    });
    return counts;
  }, [globalUsers]);

  const [roles, setRoles] = useState<{ name: string; description: string; users: number }[]>([]);

  // Initialize roles from authRoles
  useEffect(() => {
    setRoles(authRoles.map(r => ({ ...r, users: rolesCount[r.name] || 0 })));
  }, [authRoles, rolesCount]);

  const systemUsers = useMemo(() => {
    return globalUsers.map((u: any) => ({
      id: u.uid || u.id,
      name: u.name,
      email: u.email,
      role: u.role,
      avatar: u.photoURL
    }));
  }, [globalUsers]);

  useEffect(() => {
    setCompanyName(companySettings.name || '');
    setCompanyEmail(companySettings.email || '');
    setCompanyLogo(companySettings.logo || '');
    setCompanyLocation(companySettings.location || '');
    setCompanyPhone(companySettings.phone || '');
  }, [companySettings]);

  const handleSaveGeneral = async () => {
    setIsSaving(true);
    try {
      await updateCompanySettings({
        name: companyName,
        email: companyEmail,
        logo: companyLogo,
        location: companyLocation,
        phone: companyPhone
      });
      toast.success('General settings saved successfully');
    } catch (error) {
      toast.error('Failed to save settings');
    } finally {
      setIsSaving(false);
    }
  };

  const handleLogoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setCompanyLogo(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const permissionsList = [
    { id: 'dashboard', label: 'Dashboard Access', description: 'View the main system dashboard' },
    { id: 'projects', label: 'Project Management', description: 'Create, edit and delete projects' },
    { id: 'finance', label: 'Financial Records', description: 'Access to invoices, expenses and payroll' },
    { id: 'employees', label: 'Employee Directory', description: 'Manage staff profiles and attendance' },
    { id: 'crm', label: 'Sales & CRM', description: 'Manage leads, clients and opportunities' },
    { id: 'reports', label: 'Reports & Analytics', description: 'View and export system-wide reports' },
    { id: 'settings', label: 'System Configuration', description: 'Modify global application settings' },
    { id: 'users', label: 'User Management', description: 'Create, edit and manage system user accounts' },
    { id: 'operations', label: 'Operations Control', description: 'Access to operations dashboard' },
    { id: 'organization', label: 'Organization', description: 'Manage company structure' },
    { id: 'recruitment', label: 'Recruitment', description: 'Manage job openings and candidates' },
    { id: 'engineers', label: 'Engineers', description: 'Manage engineering resources' },
    { id: 'tasks', label: 'Tasks & Timesheets', description: 'Manage project tasks and time' },
    { id: 'clients', label: 'Clients', description: 'Manage client relationships' },
    { id: 'expenses', label: 'Company Expenses', description: 'Manage internal company expenses' },
    { id: 'documents', label: 'Documents', description: 'Access to document repository' },
  ];

  const handleAddUserToRole = (roleName: string) => {
    setUserData(prev => ({ ...prev, role: roleName }));
    setIsAddUserModalOpen(true);
  };

  const handleCreateUser = async () => {
    if (!userData.fullName || !userData.email || (!editingUser && !userData.password)) {
      toast.error('Please fill in all required fields');
      return;
    }

    setIsSaving(true);
    try {
      if (editingUser) {
        // Update existing user on Server
        const updatedUsers = globalUsers.map((u: any) => 
          (u.uid === editingUser || u.id === editingUser) 
            ? { ...u, name: userData.fullName, email: userData.email, role: userData.role } 
            : u
        );
        await updateSystemUsers(updatedUsers);
        toast.success(`User ${userData.fullName} updated successfully`);
      } else {
        // Create new user on Server
        const newUid = crypto.randomUUID().split('-')[0];
        const newUser = {
          uid: newUid,
          id: newUid,
          tenantId: (profile as any)?.tenantId || profile?.uid,
          name: userData.fullName,
          email: userData.email,
          username: userData.email.split('@')[0], // Use part of email as username
          password: userData.password, // In a real app, this should be hashed
          role: userData.role,
          createdAt: new Date().toISOString()
        };
        await updateSystemUsers([...globalUsers, newUser]);
        toast.success(`User ${userData.fullName} created and assigned to ${userData.role}`);
      }
      
      setIsAddUserModalOpen(false);
      setEditingUser(null);
      setUserData({
        fullName: '',
        email: '',
        password: '',
        phone: '',
        role: 'Employee'
      });
    } catch (error) {
      toast.error('Failed to save user');
    } finally {
      setIsSaving(false);
    }
  };

  const handleEditUser = (user: { id: string; name: string; email: string; role: string }) => {
    setEditingUser(user.id);
    setUserData({
      fullName: user.name,
      email: user.email,
      password: '', 
      phone: '', 
      role: user.role
    });
    setIsAddUserModalOpen(true);
  };

  const handleDeleteUser = async () => {
    if (!userToDelete) return;

    setIsSaving(true);
    try {
      const updatedUsers = globalUsers.filter((u: any) => (u.uid !== userToDelete.id && u.id !== userToDelete.id));
      await updateSystemUsers(updatedUsers);
      toast.success('User removed successfully');
      setIsDeleteModalOpen(false);
      setUserToDelete(null);
    } catch (error) {
      toast.error('Failed to delete user');
    } finally {
      setIsSaving(false);
    }
  };

  const confirmDeleteUser = (user: { id: string; name: string }) => {
    setUserToDelete(user);
    setIsDeleteModalOpen(true);
  };

  const togglePermission = async (role: string, permissionId: string) => {
    if (isSaving) return;
    setIsSaving(true);
    try {
      const current = rolePermissions[role] || [];
      const updated = current.includes(permissionId)
        ? current.filter(id => id !== permissionId)
        : [...current, permissionId];
      
      const newPermissions = { ...rolePermissions, [role]: updated };
      await updateRolePermissions(newPermissions);
      toast.success('Permission updated');
    } catch (error) {
      console.error('Toggle permission error:', error);
      toast.error('Failed to update permission');
    } finally {
      setIsSaving(false);
    }
  };

  const handleToggleAllModule = async (role: string, moduleId: string, checked: boolean) => {
    if (isSaving) return;
    setIsSaving(true);
    try {
      const module = modules.find(m => m.id === moduleId);
      if (!module) return;

      const modulePermissions = module.actions.map(action => `${moduleId}.${action}`);
      const current = rolePermissions[role] || [];
      
      let updated;
      if (checked) {
        // Add all module permissions that aren't already there
        updated = [...new Set([...current, ...modulePermissions])];
      } else {
        // Remove all module permissions
        updated = current.filter(id => !modulePermissions.includes(id));
      }

      const newPermissions = { ...rolePermissions, [role]: updated };
      await updateRolePermissions(newPermissions);
      toast.success(`${checked ? 'Granted' : 'Revoked'} all ${module.name} permissions`);
    } catch (error) {
      console.error('Toggle module error:', error);
      toast.error('Failed to update module permissions');
    } finally {
      setIsSaving(false);
    }
  };

  const handleAddRole = async () => {
    if (isSaving) return;
    if (!newRole.name || !newRole.name.trim()) {
      toast.error('Role name is required');
      return;
    }

    const roleName = newRole.name.trim();
    const roleDescription = newRole.description || '';

    setIsSaving(true);
    try {
      if (editingRole) {
        // Check if name is taken by another role
        const roleExists = roles.some(r => r.name.toLowerCase() === roleName.toLowerCase() && r.name !== editingRole);
        if (roleExists) {
          toast.error('Another role already has this name');
          setIsSaving(false);
          return;
        }

        // Update existing role
        const updatedRoles = roles.map(r => r.name === editingRole ? { ...r, name: roleName, description: roleDescription } : r);
        
        // Update server/context
        await updateRoles(updatedRoles.map(({ name, description }) => ({ name, description })));
        
        // Update permissions if name changed
        if (editingRole !== roleName) {
          const updated = { ...rolePermissions };
          updated[roleName] = updated[editingRole] || [];
          delete updated[editingRole];
          await updateRolePermissions(updated);
          
          if (selectedRole === editingRole) setSelectedRole(roleName);
        }
        
        setRoles(updatedRoles);
        toast.success('Role updated successfully');
      } else {
        // Add new role
        const roleExists = roles.some(r => r.name.toLowerCase() === roleName.toLowerCase());
        if (roleExists) {
          toast.error('Role already exists');
          setIsSaving(false);
          return;
        }

        const updatedRoles = [...roles, { name: roleName, description: roleDescription, users: 0 }];
        
        // Update server/context
        await updateRoles(updatedRoles.map(({ name, description }) => ({ name, description })));
        
        // Ensure permissions entry exists for new role
        const updatedPermissions = { ...rolePermissions };
        if (!updatedPermissions[roleName]) {
          updatedPermissions[roleName] = [];
          await updateRolePermissions(updatedPermissions);
        }
        
        setRoles(updatedRoles);
        toast.success('New role created successfully');
      }

      setIsAddRoleModalOpen(false);
      setNewRole({ name: '', description: '' });
      setEditingRole(null);
    } catch (error: any) {
      console.error('Add role error:', error);
      toast.error(`Failed to save role: ${error.message || 'Unknown error'}`);
    } finally {
      setIsSaving(false);
    }
  };

  const handleEditRole = (roleName: string) => {
    const role = roles.find(r => r.name === roleName);
    if (role) {
      setNewRole({ name: role.name, description: role.description });
      setEditingRole(roleName);
      setIsAddRoleModalOpen(true);
    }
  };

  const handleDeleteRole = async (roleName: string) => {
    if (roleName === 'Administrator') {
      toast.error('Cannot delete Administrator role');
      return;
    }
    if (isSaving) return;
    setIsSaving(true);
    try {
      const updatedRoles = roles.filter(r => r.name !== roleName);
      setRoles(updatedRoles);
      await updateRoles(updatedRoles.map(({ name, description }) => ({ name, description })));
      
      const updated = { ...rolePermissions };
      delete updated[roleName];
      await updateRolePermissions(updated);
      
      if (selectedRole === roleName) setSelectedRole('Administrator');
      toast.success(`${roleName} role deleted`);
    } catch (error) {
      console.error('Delete role error:', error);
      toast.error('Failed to delete role');
    } finally {
      setIsSaving(false);
    }
  };

  const handleDuplicateRole = async (roleName: string) => {
    const roleToCopy = roles.find(r => r.name === roleName);
    if (roleToCopy) {
      if (isSaving) return;
      setIsSaving(true);
      try {
        const newName = `${roleName} (Copy)`;
        const updatedRoles = [...roles, { ...roleToCopy, name: newName, users: 0 }];
        setRoles(updatedRoles);
        await updateRoles(updatedRoles.map(({ name, description }) => ({ name, description })));
        await updateRolePermissions({ ...rolePermissions, [newName]: [...(rolePermissions[roleName] || [])] });
        toast.success(`Duplicated ${roleName}`);
      } catch (error) {
        console.error('Duplicate role error:', error);
        toast.error('Failed to duplicate role');
      } finally {
        setIsSaving(false);
      }
    }
  };

  const handleSave = () => {
    setIsSaving(true);
    setTimeout(() => {
      setIsSaving(false);
      toast.success('Settings saved successfully');
    }, 1200);
  };

  const handleReset = async () => {
    if (isSaving) return;
    setIsSaving(true);
    try {
      await updateRoles([
        { name: 'Administrator', description: 'Full system access and configuration', users: 0 },
        { name: 'Manager', description: 'Access to departmental reports and tasks', users: 0 },
        { name: 'Employee', description: 'Standard access to personal tasks and documents', users: 0 },
        { name: 'Guest', description: 'Limited read-only access to specific projects', users: 0 },
      ]);
      await updateRolePermissions({
        'Administrator': [
          'dashboard.view',
          'crm.view', 'crm.create', 'crm.edit', 'crm.delete', 'crm.export',
          'projects.view', 'projects.view_all', 'projects.create', 'projects.edit', 'projects.delete', 'projects.export',
          'tasks.view', 'tasks.view_all', 'tasks.create', 'tasks.edit', 'tasks.delete', 'tasks.export',
          'finance.view', 'finance.create', 'finance.edit', 'finance.delete', 'finance.export',
          'hr.view', 'hr.create', 'hr.edit', 'hr.delete', 'hr.export',
          'operations.view', 'operations.create', 'operations.edit', 'operations.delete', 'operations.export',
          'documents.view', 'documents.create', 'documents.edit', 'documents.delete', 'documents.export',
          'settings.view', 'settings.edit'
        ],
        'Manager': [
          'dashboard.view',
          'crm.view', 'crm.create', 'crm.edit',
          'projects.view', 'projects.view_all', 'projects.create', 'projects.edit',
          'tasks.view', 'tasks.view_all', 'tasks.create', 'tasks.edit',
          'hr.view',
          'operations.view',
          'documents.view', 'documents.create'
        ],
        'Employee': [
          'dashboard.view',
          'projects.view',
          'tasks.view',
          'documents.view'
        ],
        'Guest': [],
      });
      toast.info('Settings reset to default');
    } catch (error) {
      console.error('Reset roles error:', error);
      toast.error('Failed to reset roles');
    } finally {
      setIsSaving(false);
    }
  };

  const handleClearAllData = async () => {
    if (!confirm('CRITICAL ACTION: This will delete ALL projects, tasks, expenses, clients, engineers, jobs, candidates, and documents from the server. This cannot be undone. Are you absolutely sure?')) {
      return;
    }

    setIsSaving(true);
    try {
      const keysToClear = [
        'projects', 'tasks', 'expenses', 'clients', 'engineers', 
        'departments', 'jobs', 'candidates', 'documents', 'leads'
      ];
      
      await Promise.all(keysToClear.map(key => storage.set(key, [])));

      toast.success('All application data has been cleared from the server');
      // Force reload to refresh state
      window.location.reload();
    } catch (error) {
      console.error('Error clearing data:', error);
      toast.error('Failed to clear data.');
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">System Settings</h1>
        <p className="text-muted-foreground">Configure global application preferences, user roles, and security protocols.</p>
      </div>

      <div className="flex flex-col lg:flex-row gap-8">
        {/* Sidebar Navigation */}
        <div className="w-full lg:w-64 space-y-1">
          <SettingsNavItem 
            icon={Globe} 
            label="General" 
            active={activeTab === 'general'} 
            onClick={() => setActiveTab('general')} 
          />
          <SettingsNavItem 
            icon={User} 
            label="User Management" 
            active={activeTab === 'users'} 
            onClick={() => setActiveTab('users')} 
          />
          <SettingsNavItem 
            icon={Shield} 
            label="Security & Privacy" 
            active={activeTab === 'security'} 
            onClick={() => setActiveTab('security')} 
          />
          <SettingsNavItem 
            icon={Bell} 
            label="Notifications" 
            active={activeTab === 'notifications'} 
            onClick={() => setActiveTab('notifications')} 
          />
          <SettingsNavItem 
            icon={Key} 
            label="Integrations & API" 
            active={activeTab === 'integrations'} 
            onClick={() => setActiveTab('integrations')} 
          />
          <SettingsNavItem 
            icon={Database} 
            label="Data Management" 
            active={activeTab === 'data'} 
            onClick={() => setActiveTab('data')} 
          />
          <SettingsNavItem 
            icon={FileArchive} 
            label="Code Import" 
            active={activeTab === 'import'} 
            onClick={() => setActiveTab('import')} 
          />
        </div>

        {/* Content Area */}
        <div className="flex-1 space-y-6">
          <div className="rounded-xl border border-border bg-card shadow-sm overflow-hidden">
            <div className="p-6 border-b border-border bg-muted/30">
              <h3 className="font-semibold capitalize">{activeTab.replace('-', ' ')} Settings</h3>
              <p className="text-xs text-muted-foreground mt-1">Manage your {activeTab} preferences and configurations.</p>
            </div>

            <div className="p-6 space-y-6">
              {activeTab === 'general' && (
                <div className="space-y-6">
                  <div className="flex flex-col md:flex-row gap-8 items-start">
                    <div className="flex flex-col items-center gap-4">
                      <div className="h-32 w-32 rounded-2xl border-2 border-dashed border-border bg-muted/30 flex items-center justify-center overflow-hidden relative group">
                        {companyLogo ? (
                          <img 
                            src={companyLogo} 
                            alt="Company Logo" 
                            className="h-full w-full object-contain"
                            referrerPolicy="no-referrer"
                          />
                        ) : (
                          <Building2 size={40} className="text-muted-foreground" />
                        )}
                        <label className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center cursor-pointer">
                          <Plus className="text-white" size={24} />
                          <input 
                            type="file" 
                            className="hidden" 
                            accept="image/*"
                            onChange={handleLogoUpload}
                          />
                        </label>
                      </div>
                      <div className="text-center">
                        <p className="text-xs font-medium">Company Logo</p>
                        <p className="text-[10px] text-muted-foreground mt-1">PNG, JPG up to 2MB</p>
                      </div>
                    </div>

                    <div className="flex-1 space-y-4 w-full">
                      <div className="grid gap-2">
                        <label className="text-sm font-medium">Company Name</label>
                        <input 
                          type="text" 
                          value={companyName}
                          onChange={(e) => setCompanyName(e.target.value)}
                          className="h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                        />
                      </div>
                      <div className="grid gap-2">
                        <label className="text-sm font-medium">Support Email</label>
                        <input 
                          type="email" 
                          value={companyEmail}
                          onChange={(e) => setCompanyEmail(e.target.value)}
                          className="h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                        />
                      </div>
                      <div className="grid gap-2">
                        <label className="text-sm font-medium">Location</label>
                        <input 
                          type="text" 
                          value={companyLocation}
                          onChange={(e) => setCompanyLocation(e.target.value)}
                          placeholder="e.g. Dubai, UAE"
                          className="h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                        />
                      </div>
                      <div className="grid gap-2">
                        <label className="text-sm font-medium">Phone Number</label>
                        <input 
                          type="text" 
                          value={companyPhone}
                          onChange={(e) => setCompanyPhone(e.target.value)}
                          placeholder="e.g. +971 4 123 4567"
                          className="h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                        />
                      </div>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="grid gap-2">
                      <label className="text-sm font-medium">Timezone</label>
                      <select className="h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20">
                        <option>(GMT-08:00) Pacific Time</option>
                        <option>(GMT-05:00) Eastern Time</option>
                        <option>(GMT+00:00) UTC</option>
                        <option>(GMT+01:00) Central European Time</option>
                      </select>
                    </div>
                    <div className="grid gap-2">
                      <label className="text-sm font-medium">Language</label>
                      <select className="h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20">
                        <option>English (US)</option>
                        <option>Spanish</option>
                        <option>French</option>
                        <option>German</option>
                      </select>
                    </div>
                  </div>

                  <div className="flex justify-end pt-4">
                    {hasPermission('settings.edit') && (
                      <button 
                        onClick={handleSaveGeneral}
                        disabled={isSaving}
                        className="flex items-center gap-2 rounded-lg bg-primary px-6 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-all disabled:opacity-50"
                      >
                        {isSaving ? <RefreshCcw className="animate-spin" size={16} /> : <Save size={16} />}
                        Save Changes
                      </button>
                    )}
                  </div>

                  <div className="pt-6 border-t border-border">
                    <h4 className="text-sm font-bold text-destructive mb-2">Danger Zone</h4>
                    <p className="text-xs text-muted-foreground mb-4">These actions are destructive and cannot be undone.</p>
                    {hasPermission('settings.edit') && (
                      <button 
                        onClick={handleClearAllData}
                        disabled={isSaving}
                        className="flex items-center gap-2 rounded-lg border border-destructive/50 bg-destructive/5 px-4 py-2 text-sm font-medium text-destructive hover:bg-destructive hover:text-destructive-foreground transition-all disabled:opacity-50"
                      >
                        <Trash2 size={16} />
                        Clear All Application Data
                      </button>
                    )}
                  </div>
                </div>
              )}

              {activeTab === 'users' && (
                <div className="space-y-8">
                  {/* User Stats Summary */}
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="p-4 rounded-2xl border border-border bg-card shadow-sm">
                      <div className="flex items-center gap-3 mb-2">
                        <div className="h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center text-primary">
                          <User size={18} />
                        </div>
                        <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Total Users</span>
                      </div>
                      <p className="text-2xl font-bold">{systemUsers.length}</p>
                    </div>
                    <div className="p-4 rounded-2xl border border-border bg-card shadow-sm">
                      <div className="flex items-center gap-3 mb-2">
                        <div className="h-8 w-8 rounded-lg bg-blue-500/10 flex items-center justify-center text-blue-500">
                          <Shield size={18} />
                        </div>
                        <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Admins</span>
                      </div>
                      <p className="text-2xl font-bold">{systemUsers.filter(u => u.role === 'Administrator').length}</p>
                    </div>
                    <div className="p-4 rounded-2xl border border-border bg-card shadow-sm">
                      <div className="flex items-center gap-3 mb-2">
                        <div className="h-8 w-8 rounded-lg bg-green-500/10 flex items-center justify-center text-green-500">
                          <Check size={18} />
                        </div>
                        <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Active Roles</span>
                      </div>
                      <p className="text-2xl font-bold">{roles.length}</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 xl:grid-cols-12 gap-8">
                    {/* Left Column: Roles */}
                    <div className="xl:col-span-4 space-y-4">
                      <div className="flex items-center justify-between px-1">
                        <h4 className="text-sm font-bold uppercase tracking-widest text-muted-foreground">System Roles</h4>
                        {hasPermission('settings.edit') && (
                          <button 
                            onClick={() => setIsAddRoleModalOpen(true)}
                            className="p-1.5 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-colors"
                            title="Add New Role"
                          >
                            <Plus size={16} />
                          </button>
                        )}
                      </div>
                      <div className="grid grid-cols-1 gap-3">
                        {roles.map((role: { name: string; description: string; users: number }) => (
                          <RoleItem 
                            key={role.name}
                            name={role.name} 
                            description={role.description} 
                            users={role.users} 
                            active={selectedRole === role.name}
                            onClick={() => setSelectedRole(role.name)}
                            isMenuOpen={activeRoleMenu === role.name}
                            onToggleMenu={() => setActiveRoleMenu(activeRoleMenu === role.name ? null : role.name)}
                            onDelete={() => handleDeleteRole(role.name)}
                            onDuplicate={() => handleDuplicateRole(role.name)}
                            onEdit={() => handleEditRole(role.name)}
                            canEdit={hasPermission('settings.edit')}
                          />
                        ))}
                      </div>
                    </div>

                    {/* Right Column: Role Details & Users */}
                    <div className="xl:col-span-8 space-y-6">
                      {selectedRole ? (
                        <motion.div 
                          key={selectedRole}
                          initial={{ opacity: 0, y: 10 }}
                          animate={{ opacity: 1, y: 0 }}
                          className="space-y-6"
                        >
                          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 bg-muted/30 p-4 rounded-2xl border border-border">
                            <div className="space-y-1">
                              <div className="flex items-center gap-2">
                                <h3 className="text-lg font-bold">{selectedRole}</h3>
                                <span className="px-2 py-0.5 rounded-full bg-primary/10 text-primary text-[10px] font-bold uppercase tracking-wider">
                                  {systemUsers.filter(u => u.role === selectedRole).length} Users
                                </span>
                              </div>
                              <p className="text-sm text-muted-foreground">
                                {roles.find(r => r.name === selectedRole)?.description}
                              </p>
                            </div>
                            <div className="flex items-center gap-2">
                              {hasPermission('settings.edit') && (
                                <>
                                  <button 
                                    onClick={() => handleEditRole(selectedRole)}
                                    className="p-2 rounded-lg border border-border bg-card hover:bg-accent transition-colors text-muted-foreground"
                                    title="Edit Role"
                                  >
                                    <Edit3 size={16} />
                                  </button>
                                  <button 
                                    onClick={() => handleAddUserToRole(selectedRole)}
                                    className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:bg-primary/90 transition-all shadow-sm"
                                  >
                                    <Plus size={16} />
                                    Add User
                                  </button>
                                </>
                              )}
                            </div>
                          </div>

                          <div className="space-y-4">
                            <div className="flex items-center gap-1 border-b border-border">
                              <button 
                                onClick={() => setUserViewTab('permissions')}
                                className={cn(
                                  "px-4 py-2 text-xs font-bold uppercase tracking-widest transition-all relative",
                                  userViewTab === 'permissions' ? "text-primary" : "text-muted-foreground hover:text-foreground"
                                )}
                              >
                                Permissions
                                {userViewTab === 'permissions' && (
                                  <motion.div layoutId="tab-underline" className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary" />
                                )}
                              </button>
                              <button 
                                onClick={() => setUserViewTab('assigned-users')}
                                className={cn(
                                  "px-4 py-2 text-xs font-bold uppercase tracking-widest transition-all relative",
                                  userViewTab === 'assigned-users' ? "text-primary" : "text-muted-foreground hover:text-foreground"
                                )}
                              >
                                Assigned Users
                                {userViewTab === 'assigned-users' && (
                                  <motion.div layoutId="tab-underline" className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary" />
                                )}
                              </button>
                            </div>

                            {userViewTab === 'permissions' ? (
                              <div className="space-y-6">
                                {modules.map((module) => {
                                  const modulePermissions = module.actions.map(action => `${module.id}.${action}`);
                                  const activeModulePermissions = (rolePermissions[selectedRole] || []).filter(p => p.startsWith(`${module.id}.`));
                                  const isAllSelected = activeModulePermissions.length === module.actions.length;
                                  const isSomeSelected = activeModulePermissions.length > 0 && !isAllSelected;

                                  return (
                                    <div key={module.id} className="rounded-2xl border border-border bg-card overflow-hidden shadow-sm">
                                      <div className="px-6 py-4 border-b border-border bg-muted/30 flex items-center justify-between">
                                        <div className="flex items-center gap-3">
                                          <div className="h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center text-primary">
                                            {module.id === 'crm' ? <TrendingUp size={18} /> : 
                                             module.id === 'projects' ? <Briefcase size={18} /> :
                                             module.id === 'finance' ? <DollarSign size={18} /> :
                                             module.id === 'hr' ? <Users size={18} /> :
                                             module.id === 'operations' ? <Target size={18} /> :
                                             <Shield size={18} />}
                                          </div>
                                          <div>
                                            <h4 className="text-sm font-bold">{module.name}</h4>
                                            <p className="text-[10px] text-muted-foreground">{module.description}</p>
                                          </div>
                                        </div>
                                        <div className="flex items-center gap-2">
                                          <span className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
                                            {activeModulePermissions.length} / {module.actions.length} Actions
                                          </span>
                                          <button 
                                            onClick={() => handleToggleAllModule(selectedRole, module.id, !isAllSelected)}
                                            className={cn(
                                              "px-3 py-1 rounded-lg text-[10px] font-bold uppercase tracking-wider transition-all",
                                              isAllSelected 
                                                ? "bg-primary/10 text-primary hover:bg-primary/20" 
                                                : "bg-muted text-muted-foreground hover:bg-accent hover:text-foreground"
                                            )}
                                          >
                                            {isAllSelected ? 'Revoke All' : 'Grant All'}
                                          </button>
                                        </div>
                                      </div>
                                      <div className="p-6 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-4">
                                        {module.actions.map((action) => {
                                          const permissionId = `${module.id}.${action}`;
                                          const isEnabled = (rolePermissions[selectedRole] || []).includes(permissionId);
                                          return (
                                            <button
                                              key={action}
                                              onClick={() => togglePermission(selectedRole, permissionId)}
                                              disabled={!hasPermission('settings.edit')}
                                              className={cn(
                                                "flex flex-col items-center justify-center gap-2 p-3 rounded-xl border transition-all group",
                                                isEnabled 
                                                  ? "border-primary/20 bg-primary/5 text-primary shadow-sm" 
                                                  : "border-border bg-card hover:border-primary/30 text-muted-foreground hover:text-foreground",
                                                !hasPermission('settings.edit') && "opacity-60 cursor-not-allowed"
                                              )}
                                            >
                                              <div className={cn(
                                                "h-5 w-5 rounded border transition-colors flex items-center justify-center",
                                                isEnabled ? "bg-primary border-primary text-white" : "border-muted-foreground/30"
                                              )}>
                                                {isEnabled && <Check size={14} strokeWidth={3} />}
                                              </div>
                                              <span className="text-[10px] font-bold uppercase tracking-widest">{action}</span>
                                            </button>
                                          );
                                        })}
                                      </div>
                                    </div>
                                  );
                                })}
                              </div>
                            ) : (
                              <div className="rounded-2xl border border-border bg-card overflow-hidden shadow-sm">
                                {systemUsers.filter(u => u.role === selectedRole).length > 0 ? (
                                  <div className="divide-y divide-border">
                                    {systemUsers.filter(u => u.role === selectedRole).map((user) => (
                                      <div key={user.id} className="flex items-center justify-between p-4 hover:bg-muted/30 transition-colors group">
                                        <div className="flex items-center gap-4">
                                          <div className="relative">
                                            <div className="h-12 w-12 rounded-full bg-gradient-to-br from-primary/20 to-primary/5 flex items-center justify-center text-primary font-bold text-sm border border-primary/10">
                                              {user.name.split(' ').map(n => n[0]).join('')}
                                            </div>
                                            <div className="absolute -bottom-0.5 -right-0.5 h-4 w-4 rounded-full bg-green-500 border-2 border-card" />
                                          </div>
                                          <div>
                                            <p className="text-sm font-bold">{user.name}</p>
                                            <div className="flex items-center gap-2 text-xs text-muted-foreground mt-0.5">
                                              <Mail size={12} />
                                              {user.email}
                                            </div>
                                          </div>
                                        </div>
                                        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                          {hasPermission('settings.edit') && (
                                            <>
                                              <button 
                                                onClick={() => handleEditUser(user)}
                                                className="p-2 rounded-lg text-muted-foreground hover:text-primary hover:bg-primary/10 transition-all"
                                                title="Edit User"
                                              >
                                                <Edit3 size={16} />
                                              </button>
                                              <button 
                                                onClick={() => confirmDeleteUser({ id: user.id, name: user.name })}
                                                className="p-2 rounded-lg text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-all"
                                                title="Delete User"
                                              >
                                                <Trash2 size={16} />
                                              </button>
                                            </>
                                          )}
                                        </div>
                                      </div>
                                    ))}
                                  </div>
                                ) : (
                                  <div className="p-12 text-center">
                                    <div className="mx-auto h-16 w-16 rounded-full bg-muted/30 flex items-center justify-center text-muted-foreground/30 mb-4">
                                      <User size={32} />
                                    </div>
                                    <p className="text-sm font-bold text-foreground">No users assigned</p>
                                    <p className="text-xs text-muted-foreground mt-1 max-w-[200px] mx-auto">
                                      There are currently no users assigned to the {selectedRole} role.
                                    </p>
                                    <button 
                                      onClick={() => handleAddUserToRole(selectedRole)}
                                      className="mt-6 text-xs font-bold text-primary hover:underline flex items-center gap-2 mx-auto"
                                    >
                                      <Plus size={14} />
                                      Assign the first user
                                    </button>
                                  </div>
                                )}
                              </div>
                            )}
                          </div>
                        </motion.div>
                      ) : (
                        <div className="h-full flex flex-col items-center justify-center p-12 text-center bg-muted/10 rounded-3xl border border-dashed border-border">
                          <Shield size={48} className="text-muted-foreground/20 mb-4" />
                          <h3 className="text-lg font-bold text-muted-foreground">Select a Role</h3>
                          <p className="text-sm text-muted-foreground/60 mt-2 max-w-xs">
                            Choose a role from the left to manage its permissions and assigned users.
                          </p>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}

              {activeTab === 'security' && (
                <div className="space-y-6">
                  <div className="flex items-center justify-between p-4 rounded-lg border border-border bg-accent/30">
                    <div className="flex items-center gap-4">
                      <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center text-primary">
                        <Lock size={20} />
                      </div>
                      <div>
                        <p className="text-sm font-medium">Two-Factor Authentication</p>
                        <p className="text-xs text-muted-foreground">Add an extra layer of security to your account.</p>
                      </div>
                    </div>
                    <div className="h-6 w-11 rounded-full bg-primary relative cursor-pointer transition-colors">
                      <div className="absolute right-1 top-1 h-4 w-4 rounded-full bg-white shadow-sm" />
                    </div>
                  </div>
                  <div className="space-y-4">
                    <h4 className="text-sm font-semibold">Password Policy</h4>
                    <div className="space-y-2">
                      <div className="flex items-center gap-2 text-xs text-muted-foreground">
                        <div className="h-1.5 w-1.5 rounded-full bg-green-500" />
                        Minimum 12 characters
                      </div>
                      <div className="flex items-center gap-2 text-xs text-muted-foreground">
                        <div className="h-1.5 w-1.5 rounded-full bg-green-500" />
                        Include special characters
                      </div>
                      <div className="flex items-center gap-2 text-xs text-muted-foreground">
                        <div className="h-1.5 w-1.5 rounded-full bg-yellow-500" />
                        Require password change every 90 days
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {activeTab === 'notifications' && (
                <div className="space-y-4">
                  <NotificationToggle label="Email Notifications" description="Receive updates via email" active={true} />
                  <NotificationToggle label="Push Notifications" description="Receive updates on your desktop" active={false} />
                  <NotificationToggle label="Project Updates" description="Get notified when project status changes" active={true} />
                  <NotificationToggle label="Task Assignments" description="Get notified when a new task is assigned" active={true} />
                </div>
              )}

              {activeTab === 'integrations' && (
                <div className="space-y-4">
                  <div className="grid gap-2">
                    <label className="text-sm font-medium">API Key</label>
                    <div className="flex gap-2">
                      <input 
                        type="password" 
                        defaultValue="sk_test_51Mz9jL2eZ..." 
                        readOnly
                        className="h-10 flex-1 rounded-lg border border-border bg-muted px-3 text-sm focus:outline-none"
                      />
                      <button 
                        onClick={() => toast.success('API Key copied to clipboard')}
                        className="px-4 rounded-lg border border-border bg-card text-xs font-medium hover:bg-accent transition-colors"
                      >
                        Copy
                      </button>
                    </div>
                  </div>
                  <div className="pt-4 border-t border-border">
                    <h4 className="text-sm font-semibold mb-4">Connected Apps</h4>
                    <div className="space-y-3">
                      <ConnectedApp name="Slack" status="Connected" />
                      <ConnectedApp name="GitHub" status="Connected" />
                      <ConnectedApp name="Jira" status="Disconnected" />
                    </div>
                  </div>
                </div>
              )}

              {activeTab === 'data' && (
                <DataManagement />
              )}

              {activeTab === 'import' && (
                <CodeImport />
              )}
            </div>

            <div className="p-6 border-t border-border bg-muted/30 flex items-center justify-between">
              {hasPermission('settings.edit') ? (
                <button 
                  onClick={handleReset}
                  className="flex items-center gap-2 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
                >
                  <RefreshCcw size={16} />
                  Reset to Default
                </button>
              ) : (
                <div />
              )}
              <div className="flex items-center gap-3">
                <button 
                  onClick={() => toast.info('Changes discarded')}
                  className="px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
                >
                  Cancel
                </button>
                <button 
                  onClick={handleSave}
                  disabled={isSaving}
                  className={cn(
                    "flex items-center gap-2 rounded-lg bg-primary px-6 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors shadow-sm disabled:opacity-70 disabled:cursor-not-allowed min-w-[140px] justify-center"
                  )}
                >
                  {isSaving ? (
                    <>
                      <RefreshCcw size={18} className="animate-spin" />
                      Saving...
                    </>
                  ) : (
                    <>
                      <Save size={18} />
                      Save Changes
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Delete User Confirmation Modal */}
      <AnimatePresence>
        {isDeleteModalOpen && userToDelete && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="w-full max-w-sm rounded-2xl border border-border bg-card p-6 shadow-xl"
            >
              <div className="flex flex-col items-center text-center">
                <div className="mb-4 rounded-full bg-destructive/10 p-3 text-destructive">
                  <AlertCircle size={32} />
                </div>
                <h3 className="text-lg font-bold">Remove User</h3>
                <p className="mt-2 text-sm text-muted-foreground">
                  Are you sure you want to remove <span className="font-bold text-foreground">{userToDelete.name}</span>? 
                  This will revoke their access to the system.
                </p>
              </div>

              <div className="mt-6 flex gap-3">
                <button 
                  onClick={() => setIsDeleteModalOpen(false)}
                  className="flex-1 rounded-xl border border-border px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button 
                  onClick={handleDeleteUser}
                  disabled={isSaving}
                  className="flex-1 rounded-xl bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground hover:bg-destructive/90 transition-colors disabled:opacity-50"
                >
                  {isSaving ? 'Removing...' : 'Remove User'}
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Add Role Modal */}
      <AnimatePresence>
        {isAddRoleModalOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsAddRoleModalOpen(false)}
              className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              className="fixed left-1/2 top-1/2 z-[51] w-[95vw] max-w-md -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-border bg-card p-6 shadow-2xl"
            >
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold">{editingRole ? 'Edit Role' : 'Create New Role'}</h2>
                <button 
                  onClick={() => {
                    setIsAddRoleModalOpen(false);
                    setEditingRole(null);
                    setNewRole({ name: '', description: '' });
                  }}
                  className="rounded-full p-1 hover:bg-accent transition-colors"
                >
                  <X size={20} />
                </button>
              </div>
              
              <div className="space-y-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Role Name</label>
                  <input 
                    type="text" 
                    placeholder="e.g. Project Lead"
                    value={newRole.name}
                    onChange={(e) => setNewRole({ ...newRole, name: e.target.value })}
                    className="w-full h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Description</label>
                  <textarea 
                    placeholder="What can this role do?"
                    value={newRole.description}
                    onChange={(e) => setNewRole({ ...newRole, description: e.target.value })}
                    className="w-full min-h-[100px] rounded-lg border border-border bg-background p-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                
                <div className="flex gap-3 pt-4">
                  <button 
                    onClick={() => {
                      setIsAddRoleModalOpen(false);
                      setEditingRole(null);
                      setNewRole({ name: '', description: '' });
                    }}
                    className="flex-1 h-10 rounded-lg border border-border text-sm font-medium hover:bg-accent transition-colors"
                  >
                    Cancel
                  </button>
                  <button 
                    onClick={handleAddRole}
                    className="flex-1 h-10 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors"
                  >
                    {editingRole ? 'Save Changes' : 'Create Role'}
                  </button>
                </div>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>

      {/* Add User Modal */}
      <AnimatePresence>
        {isAddUserModalOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsAddUserModalOpen(false)}
              className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              className="fixed left-1/2 top-1/2 z-[51] w-[95vw] max-w-md -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-border bg-card p-6 shadow-2xl"
            >
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold">{editingUser ? 'Edit User' : 'Add New User'}</h2>
                <button 
                  onClick={() => {
                    setIsAddUserModalOpen(false);
                    setEditingUser(null);
                    setUserData({ fullName: '', email: '', password: '', phone: '', role: 'Administrator' });
                  }}
                  className="rounded-full p-1 hover:bg-accent transition-colors"
                >
                  <X size={20} />
                </button>
              </div>

              <div className="space-y-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Full Name</label>
                  <div className="relative">
                    <User className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={16} />
                    <input 
                      type="text" 
                      value={userData.fullName}
                      onChange={(e) => setUserData({ ...userData, fullName: e.target.value })}
                      placeholder="John Doe"
                      className="w-full h-10 pl-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    />
                  </div>
                </div>
                
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <label className="text-sm font-medium">Email Address</label>
                    <div className="relative">
                      <Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={16} />
                      <input 
                        type="email" 
                        value={userData.email}
                        onChange={(e) => setUserData({ ...userData, email: e.target.value })}
                        placeholder="john@example.com"
                        className="w-full h-10 pl-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                      />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium">Phone Number</label>
                    <div className="relative">
                      <Phone className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={16} />
                      <input 
                        type="tel" 
                        value={userData.phone}
                        onChange={(e) => setUserData({ ...userData, phone: e.target.value })}
                        placeholder="+1 (555) 000-0000"
                        className="w-full h-10 pl-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                      />
                    </div>
                  </div>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-medium">Password {editingUser && <span className="text-[10px] text-muted-foreground">(Leave blank to keep current)</span>}</label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={16} />
                    <input 
                      type="password" 
                      value={userData.password}
                      onChange={(e) => setUserData({ ...userData, password: e.target.value })}
                      placeholder={editingUser ? "••••••••" : "Create a password"}
                      className="w-full h-10 pl-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-medium">Assign Role</label>
                  <select 
                    value={userData.role}
                    onChange={(e) => setUserData({ ...userData, role: e.target.value })}
                    className="w-full h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  >
                    {roles.map(role => (
                      <option key={role.name} value={role.name}>{role.name}</option>
                    ))}
                  </select>
                </div>

                <button 
                  onClick={handleCreateUser}
                  className="w-full h-10 mt-2 rounded-lg bg-primary text-sm font-semibold text-primary-foreground hover:bg-primary/90 transition-colors"
                >
                  {editingUser ? 'Update User Details' : 'Create User Account'}
                </button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}

function SettingsNavItem({ icon: Icon, label, active, onClick }: { icon: any, label: string, active: boolean, onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      className={cn(
        "w-full flex items-center justify-between px-4 py-3 rounded-lg text-sm font-medium transition-all group",
        active 
          ? "bg-primary text-primary-foreground shadow-sm" 
          : "text-muted-foreground hover:bg-accent hover:text-foreground"
      )}
    >
      <div className="flex items-center gap-3">
        <Icon size={18} />
        {label}
      </div>
      <ChevronRight size={14} className={cn("transition-transform", active ? "translate-x-0" : "-translate-x-2 opacity-0 group-hover:translate-x-0 group-hover:opacity-100")} />
    </button>
  );
}

interface RoleItemProps {
  name: string;
  description: string;
  users: number;
  active?: boolean;
  onClick?: () => void;
  isMenuOpen?: boolean;
  onToggleMenu?: () => void;
  onDelete?: () => void;
  onDuplicate?: () => void;
  onEdit?: () => void;
}

const RoleItem: React.FC<RoleItemProps> = ({ 
  name, 
  description, 
  users, 
  active, 
  onClick,
  isMenuOpen,
  onToggleMenu,
  onDelete,
  onDuplicate,
  onEdit
}) => {
  return (
    <div 
      onClick={onClick}
      className={cn(
        "group relative flex flex-col p-4 rounded-2xl border transition-all cursor-pointer overflow-hidden",
        active 
          ? "border-primary bg-primary/5 shadow-md ring-1 ring-primary/20" 
          : "border-border bg-card hover:border-primary/30 hover:shadow-sm"
      )}
    >
      {active && (
        <div className="absolute top-0 right-0 p-2">
          <div className="h-2 w-2 rounded-full bg-primary animate-pulse" />
        </div>
      )}
      
      <div className="flex items-start justify-between mb-3">
        <div className="h-10 w-10 rounded-xl bg-muted group-hover:bg-primary/10 flex items-center justify-center text-muted-foreground group-hover:text-primary transition-colors">
          {name === 'Administrator' ? <Shield size={20} /> : 
           name === 'Manager' ? <User size={20} /> : 
           <Globe size={20} />}
        </div>
        <div className="relative">
          <button 
            onClick={(e) => {
              e.stopPropagation();
              onToggleMenu?.();
            }}
            className={cn(
              "p-1.5 rounded-lg transition-colors",
              isMenuOpen ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-accent hover:text-foreground"
            )}
          >
            <MoreHorizontal size={16} />
          </button>

          <AnimatePresence>
            {isMenuOpen && (
              <>
                <div 
                  className="fixed inset-0 z-10" 
                  onClick={(e) => {
                    e.stopPropagation();
                    onToggleMenu?.();
                  }}
                />
                <motion.div
                  initial={{ opacity: 0, scale: 0.95, y: 10 }}
                  animate={{ opacity: 1, scale: 1, y: 0 }}
                  exit={{ opacity: 0, scale: 0.95, y: 10 }}
                  className="absolute right-0 mt-2 w-40 origin-top-right rounded-xl border border-border bg-card p-1 shadow-2xl z-20"
                >
                  <button 
                    onClick={(e) => {
                      e.stopPropagation();
                      onEdit?.();
                      onToggleMenu?.();
                    }}
                    className="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-xs font-bold text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
                  >
                    <Edit3 size={14} />
                    Edit Role
                  </button>
                  <button 
                    onClick={(e) => {
                      e.stopPropagation();
                      onDuplicate?.();
                      onToggleMenu?.();
                    }}
                    className="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-xs font-bold text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
                  >
                    <Copy size={14} />
                    Duplicate
                  </button>
                  <div className="my-1 border-t border-border" />
                  <button 
                    onClick={(e) => {
                      e.stopPropagation();
                      onDelete?.();
                      onToggleMenu?.();
                    }}
                    className="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-xs font-bold text-destructive hover:bg-destructive/10 transition-colors"
                  >
                    <Trash size={14} />
                    Delete Role
                  </button>
                </motion.div>
              </>
            )}
          </AnimatePresence>
        </div>
      </div>

      <div className="space-y-1">
        <h4 className="text-sm font-bold leading-none">{name}</h4>
        <p className="text-xs text-muted-foreground line-clamp-2 leading-relaxed">{description}</p>
      </div>

      <div className="mt-4 pt-4 border-t border-border/50 flex items-center justify-between">
        <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">{users} Users</span>
        <ChevronRight size={14} className={cn("transition-transform", active ? "text-primary translate-x-0" : "text-muted-foreground -translate-x-2 opacity-0 group-hover:translate-x-0 group-hover:opacity-100")} />
      </div>
    </div>
  );
};

function NotificationToggle({ label, description, active }: { label: string, description: string, active: boolean }) {
  const [enabled, setEnabled] = useState(active);
  return (
    <div className="flex items-center justify-between p-4 rounded-lg border border-border bg-accent/30">
      <div>
        <p className="text-sm font-medium">{label}</p>
        <p className="text-xs text-muted-foreground">{description}</p>
      </div>
      <div 
        onClick={() => setEnabled(!enabled)}
        className={cn(
          "h-6 w-11 rounded-full relative cursor-pointer transition-colors",
          enabled ? "bg-primary" : "bg-muted"
        )}
      >
        <div className={cn(
          "absolute top-1 h-4 w-4 rounded-full bg-white shadow-sm transition-all",
          enabled ? "right-1" : "left-1"
        )} />
      </div>
    </div>
  );
}

function ConnectedApp({ name, status }: { name: string, status: 'Connected' | 'Disconnected' }) {
  return (
    <div className="flex items-center justify-between p-3 rounded-lg border border-border">
      <div className="flex items-center gap-3">
        <div className="h-8 w-8 rounded bg-muted flex items-center justify-center font-bold text-xs">
          {name[0]}
        </div>
        <span className="text-sm font-medium">{name}</span>
      </div>
      <div className="flex items-center gap-3">
        <span className={cn(
          "text-[10px] font-bold uppercase tracking-wider",
          status === 'Connected' ? "text-green-500" : "text-muted-foreground"
        )}>
          {status}
        </span>
        <button 
          onClick={() => toast.info(`${status === 'Connected' ? 'Disconnecting' : 'Connecting'} ${name}...`)}
          className="text-xs font-medium text-primary hover:underline"
        >
          {status === 'Connected' ? 'Manage' : 'Connect'}
        </button>
      </div>
    </div>
  );
}
