import * as React from 'react';
import { useState, useEffect } from 'react';
import ConfirmationDialog from '../components/UI/ConfirmationDialog';
import { 
  User, 
  Shield, 
  Bell, 
  Lock, 
  Eye, 
  EyeOff, 
  Palette,
  Save,
  AlertTriangle,
  CheckCircle,
  X,
  Smartphone,
  Mail,
  Phone,
  MapPin,
  Users,
  Settings as SettingsIcon,
  UserPlus,
  Plus,
  Trash2,
  Crown,
  Key,
  Edit,
  Search,
  Filter
} from 'lucide-react';
import RoleModal from '../components/UI/RoleModal';
import PermissionModal from '../components/UI/PermissionModal';
import { PermissionButton } from '../components/UI/PermissionComponents';
import { useAuth } from '../context/AuthContext';
import { useNavigate } from 'react-router-dom';
import { roleApi, authApi, contactApi } from '../services/api';

const Settings: React.FC = () => {
  const { user, hasRole, isSuperAdmin } = useAuth();
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('profile');
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [notifications, setNotifications] = useState({
    email: true,
    push: true,
    sms: false,
    securityAlerts: true,
    messageNotifications: true,
    systemUpdates: false
  });
  const [privacy, setPrivacy] = useState({
    showOnlineStatus: true,
    allowDirectMessages: true,
    showInDirectory: true,
    dataSharing: false
  });
  const [preferences, setPreferences] = useState({
    theme: 'light',
    language: 'en',
    timezone: 'UTC+6',
    dateFormat: 'DD/MM/YYYY'
  });

  const [profileData, setProfileData] = useState({
    name: user?.name || '',
    rank: 'Captain', // Fallback since rank is not directly available
    unit: 'Naval Headquarters', // Fallback since unit is not directly available
    email: user?.email || 'nazrul.islam@navy.mil',
    phone: user?.phone || '+8801717171717',
    address: 'Naval Base, Dhaka, Bangladesh'
  });

  const [passwordData, setPasswordData] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  });

  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // Modal states
  const [roleModal, setRoleModal] = useState<{
    isOpen: boolean;
    mode: 'create' | 'edit';
    role: any | null;
  }>({
    isOpen: false,
    mode: 'create',
    role: null
  });

  const [permissionModal, setPermissionModal] = useState<{
    isOpen: boolean;
    mode: 'create' | 'edit';
    permission: any | null;
  }>({
    isOpen: false,
    mode: 'create',
    permission: null
  });

  const [confirmationDialog, setConfirmationDialog] = useState<{
    isOpen: boolean;
    title: string;
    message: string;
    onConfirm: () => void;
    isLoading: boolean;
  }>({
    isOpen: false,
    title: '',
    message: '',
    onConfirm: () => {},
    isLoading: false
  });

  // Fetch roles and permissions from API
  useEffect(() => {
    const fetchRolesAndPermissions = async () => {
      // Only fetch if user is authenticated
      if (!user) {
        return;
      }
      
      try {
        setRolesLoading(true);
        setPermissionsLoading(true);
        
        // Fetch roles with permissions
        const rolesResponse = await roleApi.getRolesWithPermissions();
        if (rolesResponse.status === 'success' && rolesResponse.data) {
          setRoles(rolesResponse.data.roles || []);
        } else {
          setRolesError(rolesResponse.message || 'Failed to load roles');
        }
        
        // Fetch permissions
        const permissionsResponse = await roleApi.getPermissions();
        if (permissionsResponse.status === 'success' && permissionsResponse.data) {
          setPermissions(permissionsResponse.data.permissions || []);
        } else {
          setPermissionsError(permissionsResponse.message || 'Failed to load permissions');
        }
        
      } catch (error) {
        console.error('Error fetching roles and permissions:', error);
        setRolesError('Failed to load roles');
        setPermissionsError('Failed to load permissions');
      } finally {
        setRolesLoading(false);
        setPermissionsLoading(false);
      }
    };

    fetchRolesAndPermissions();
  }, [user]);

  // Access control - only Super Admin and Admin can access Settings
  useEffect(() => {
    if (!user) {
      navigate('/login');
      return;
    }
    
    // Super Admin always has access
    if (isSuperAdmin()) {
      return;
    }
    
    // Check if user has Admin role or settings.access permission
    if (!hasRole('Admin') && !user?.permissions?.includes('settings.access')) {
      navigate('/dashboard');
      return;
    }
  }, [user, hasRole, isSuperAdmin, navigate]);

  // Don't render if user doesn't have access
  if (!user) {
    return null;
  }
  
  // Super Admin always has access
  if (isSuperAdmin()) {
    // Continue rendering
  } else if (!hasRole('Admin') && !user?.permissions?.includes('settings.access')) {
    return null;
  }

  // User management state
  const [users, setUsers] = useState<any[]>([]);
  const [usersLoading, setUsersLoading] = useState(false);
  const [usersError, setUsersError] = useState<string | null>(null);
  const [usersPagination, setUsersPagination] = useState({
    currentPage: 1,
    totalPages: 1,
    totalUsers: 0,
    usersPerPage: 10
  });

  // User delete confirmation state
  const [isUserDeleteConfirmOpen, setIsUserDeleteConfirmOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<{
    id: number;
    name: string;
  } | null>(null);

  // Roles state for dynamic role dropdown
  const [availableRoles, setAvailableRoles] = useState<any[]>([]);

  // Role management state
  const [roles, setRoles] = useState<any[]>([]);
  const [rolesLoading, setRolesLoading] = useState(false);
  const [rolesError, setRolesError] = useState<string | null>(null);

  // Permission management state
  const [permissions, setPermissions] = useState<any[]>([]);
  const [permissionsLoading, setPermissionsLoading] = useState(false);
  const [permissionsError, setPermissionsError] = useState<string | null>(null);

  // Search states
  const [roleSearchQuery, setRoleSearchQuery] = useState('');
  const [permissionSearchQuery, setPermissionSearchQuery] = useState('');
  const [userSearchQuery, setUserSearchQuery] = useState('');
  const [roleFilterLevel, setRoleFilterLevel] = useState('all');
  const [permissionFilterResource, setPermissionFilterResource] = useState('all');
  const [userFilterRole, setUserFilterRole] = useState('all');
  const [userFilterStatus, setUserFilterStatus] = useState('all');

  const tabs = [
    { id: 'profile', label: 'Profile', icon: User },
    { id: 'security', label: 'Security', icon: Shield },
    { id: 'notifications', label: 'Notifications', icon: Bell },
    { id: 'privacy', label: 'Privacy', icon: Lock },
    { id: 'preferences', label: 'Preferences', icon: Palette },
    { id: 'roles', label: 'Roles', icon: Crown },
    { id: 'permissions', label: 'Permissions', icon: Key },
    { id: 'users', label: 'User Management', icon: Users }
  ];

  const handleProfileSave = () => {
    // Simulate API call
    setTimeout(() => {
      setMessage({ type: 'success', text: 'Profile updated successfully!' });
      setTimeout(() => setMessage(null), 3000);
    }, 500);
  };

  // Fetch roles from database (excluding Super Admin)
  const fetchRoles = async () => {
    try {
      setRolesLoading(true);
      
      // API call to backend
      const response = await fetch('/api/roles', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('authToken')}`,
          'Content-Type': 'application/json'
        }
      });
      
      if (!response.ok) {
        throw new Error('Failed to fetch roles');
      }
      
      const data = await response.json();
      
      if (data.status === 'success') {
        // Filter out Super Admin role (both 'Super Admin' and 'Super_admin')
        const filteredRoles = data.data.filter((role: any) => 
          role.name !== 'Super Admin' && role.name !== 'Super_admin'
        );
        setAvailableRoles(filteredRoles);
      } else {
        throw new Error(data.message || 'Failed to fetch roles');
      }
    } catch (error: any) {
      console.error('Error fetching roles:', error);
      
      // Fallback to mock roles (excluding Super Admin)
      const mockRoles = [
        { id: 2, name: 'Admin', description: 'Administrator role' },
        { id: 3, name: 'Manager', description: 'Manager role' },
        { id: 4, name: 'Officer', description: 'Officer role' },
        { id: 5, name: 'User', description: 'Regular user role' },
        { id: 6, name: 'Navy_admin', description: 'Navy Admin role' }
      ];
      setAvailableRoles(mockRoles);
    } finally {
      setRolesLoading(false);
    }
  };

  // User management functions
  const fetchUsers = async (page = 1, searchQuery = '', roleFilter = 'all', statusFilter = 'all') => {
    try {
      setUsersLoading(true);
      setUsersError(null);
      
      console.log('🔍 Fetching users from contact API...');
      
      // Use contactApi to fetch users
      const response = await contactApi.getContacts({
        page,
        limit: usersPagination.usersPerPage,
        search: searchQuery,
        role_filter: roleFilter === 'all' ? undefined : roleFilter,
        include_inactive: statusFilter === 'all' || statusFilter === 'inactive',
        tree: false
      });
      
      console.log('📦 Contact API response:', response);
      
      if (response.status === 'success' && response.data) {
        // Convert contacts to users format
        const users = response.data.contacts.map(contact => ({
          id: contact.id,
          name: contact.name,
          service_no: contact.service_no,
          rank: contact.rank_name || contact.rank,
          role: contact.role_name || contact.role,
          designation: contact.designation_name || contact.designation,
          is_active: contact.is_active,
          last_active: contact.last_seen ? new Date(contact.last_seen).toLocaleString() : 'Never',
          unit: contact.unit_name || contact.unit,
          email: contact.email,
          phone: contact.phone,
          mobile: contact.mobile
        }));
        
        console.log('✅ Users fetched successfully:', users.length, 'users');
        setUsers(users);
        setUsersPagination(prev => ({
          ...prev,
          currentPage: response.data.pagination?.page || page,
          totalPages: response.data.pagination && response.data.pagination.limit && response.data.pagination.total
            ? Math.max(1, Math.ceil(response.data.pagination.total / response.data.pagination.limit))
            : 1,
          totalUsers: response.data.pagination?.total ?? users.length
        }));
      } else {
        console.error('❌ API returned error status:', response.message);
        throw new Error(response.message || 'Failed to fetch users');
      }
    } catch (error: any) {
      console.error('❌ Error fetching users:', error);
      console.error('❌ Error details:', error.message);
      setUsersError(error.message || 'Failed to fetch users');
    } finally {
      setUsersLoading(false);
    }
  };

  const handleUserPageChange = (page: number) => {
    setUsersPagination(prev => ({ ...prev, currentPage: page }));
    fetchUsers(page, userSearchQuery, userFilterRole, userFilterStatus);
  };

  const handleUserSearch = () => {
    setUsersPagination(prev => ({ ...prev, currentPage: 1 }));
    fetchUsers(1, userSearchQuery, userFilterRole, userFilterStatus);
  };

  // Filter users function for local filtering
  const getFilteredUsers = () => {
    if (!users || !Array.isArray(users)) {
      return [];
    }
    
    let filtered = users;
    
    if (userSearchQuery) {
      filtered = filtered.filter(user => 
        user.name?.toLowerCase().includes(userSearchQuery.toLowerCase()) ||
        user.email?.toLowerCase().includes(userSearchQuery.toLowerCase()) ||
        user.unit?.toLowerCase().includes(userSearchQuery.toLowerCase()) ||
        user.role?.toLowerCase().includes(userSearchQuery.toLowerCase())
      );
    }
    
    if (userFilterRole !== 'all') {
      filtered = filtered.filter(user => user.role === userFilterRole);
    }
    
    if (userFilterStatus !== 'all') {
      filtered = filtered.filter(user => 
        userFilterStatus === 'active' ? user.is_active : !user.is_active
      );
    }
    
    return filtered;
  };

  // User management functions
  const handleViewUser = (user: any) => {
    console.log('Viewing user:', user);
    // You can implement a modal or navigate to user details page
    alert(`Viewing user: ${user.name}\nRole: ${user.role}\nStatus: ${user.is_active ? 'Active' : 'Inactive'}`);
  };

  const handleEditUser = (user: any) => {
    console.log('Editing user:', user);
    // You can implement an edit modal or navigate to edit page
    alert(`Editing user: ${user.name}\nCurrent role: ${user.role}\nCurrent status: ${user.is_active ? 'Active' : 'Inactive'}`);
  };

  const handleUserRoleChange = (userId: number, newRole: string) => {
    console.log(`Changing user ${userId} role to ${newRole}`);
    
    // Permission check: Cannot change your own role
    if (user && userId === user.id) {
      setMessage({ type: 'error', text: 'You cannot change your own role!' });
      setTimeout(() => setMessage(null), 5000);
      return;
    }
    
    // Permission check: Cannot change Super Admin role
    const targetUser = users.find(u => u.id === userId);
    if (targetUser && (targetUser.role === 'Super Admin' || targetUser.role === 'Super_admin')) {
      setMessage({ type: 'error', text: 'Cannot change Super Admin role!' });
      setTimeout(() => setMessage(null), 5000);
      return;
    }
    
    // Update local state immediately for better UX
    setUsers(prev => prev.map(user => 
      user.id === userId ? { ...user, role: newRole } : user
    ));
    
    // Show success message
    setMessage({ type: 'success', text: `User role updated to ${newRole} successfully!` });
    setTimeout(() => setMessage(null), 3000);
    
    // Make API call to update role in database
    updateUserRoleInDatabase(userId, newRole);
  };

  const updateUserRoleInDatabase = async (userId: number, newRole: string) => {
    try {
      const response = await fetch(`/api/users/${userId}/role`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('authToken')}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ role: newRole })
      });

      if (!response.ok) {
        throw new Error('Failed to update user role');
      }

      const data = await response.json();
      
      if (data.status === 'success') {
        console.log('User role updated in database successfully');
      } else {
        throw new Error(data.message || 'Failed to update user role');
      }
    } catch (error: any) {
      console.error('Error updating user role:', error);
      
      // Revert local state on error
      setUsers(prev => prev.map(user => 
        user.id === userId ? { ...user, role: user.role } : user
      ));
      
      setMessage({ type: 'error', text: `Failed to update user role: ${error.message}` });
      setTimeout(() => setMessage(null), 5000);
    }
  };

  const handleUserStatusChange = async (userId: number, isActive: boolean) => {
    console.log(`Changing user ${userId} status to ${isActive ? 'active' : 'inactive'}`);
    
    // Permission check: Cannot modify yourself
    if (user && userId === user.id) {
      setMessage({ type: 'error', text: 'You cannot modify your own status!' });
      setTimeout(() => setMessage(null), 5000);
      return;
    }
    
    // Permission check: Cannot modify users with higher or equal ID (hierarchy protection)
    if (user && userId <= user.id) {
      setMessage({ type: 'error', text: 'You cannot modify users with equal or higher hierarchy level!' });
      setTimeout(() => setMessage(null), 5000);
      return;
    }
    
    try {
      // Make API call to update user status
      const response = await fetch(`/api/users/${userId}/status`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('authToken')}`
        },
        body: JSON.stringify({ is_active: isActive })
      });

      if (response.ok) {
        // Update local state
        setUsers(prev => prev.map(user => 
          user.id === userId ? { ...user, is_active: isActive } : user
        ));
        
        // Show success message
        setMessage({ type: 'success', text: `User status updated to ${isActive ? 'active' : 'inactive'} successfully!` });
        setTimeout(() => setMessage(null), 3000);
      } else {
        throw new Error('Failed to update user status');
      }
    } catch (error) {
      console.error('Error updating user status:', error);
      setMessage({ type: 'error', text: 'Failed to update user status' });
      setTimeout(() => setMessage(null), 5000);
    }
  };

  const handleDeleteUser = (userId: number, userName: string) => {
    // Permission check: Cannot delete yourself
    if (user && userId === user.id) {
      setMessage({ type: 'error', text: 'You cannot delete yourself!' });
      setTimeout(() => setMessage(null), 5000);
      return;
    }
    
    // Permission check: Cannot delete users with higher or equal ID (hierarchy protection)
    if (user && userId <= user.id) {
      setMessage({ type: 'error', text: 'You cannot delete users with equal or higher hierarchy level!' });
      setTimeout(() => setMessage(null), 5000);
      return;
    }
    
    setUserToDelete({ id: userId, name: userName });
    setIsUserDeleteConfirmOpen(true);
  };

  const confirmDeleteUser = async () => {
    if (!userToDelete) return;
    
    try {
      // Make API call to delete user
      const response = await fetch(`/api/users/${userToDelete.id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('authToken')}`
        }
      });

      if (response.ok) {
        // Update local state
        setUsers(prev => prev.filter(user => user.id !== userToDelete.id));
        
        // Show success message
        setMessage({ type: 'success', text: 'User deleted successfully!' });
        setTimeout(() => setMessage(null), 3000);
      } else {
        throw new Error('Failed to delete user');
      }
    } catch (error) {
      console.error('Error deleting user:', error);
      setMessage({ type: 'error', text: 'Failed to delete user' });
      setTimeout(() => setMessage(null), 5000);
    } finally {
      setIsUserDeleteConfirmOpen(false);
      setUserToDelete(null);
    }
  };

  const cancelDeleteUser = () => {
    setIsUserDeleteConfirmOpen(false);
    setUserToDelete(null);
  };

  // Load data on component mount
  useEffect(() => {
    fetchUsers();
    fetchRoles(); // Load available roles for dropdown
  }, []);

  const handlePasswordChange = async () => {
    if (passwordData.newPassword !== passwordData.confirmPassword) {
      setMessage({ type: 'error', text: 'New passwords do not match!' });
      setTimeout(() => setMessage(null), 3000);
      return;
    }
    
    if (passwordData.newPassword.length < 6) {
      setMessage({ type: 'error', text: 'New password must be at least 6 characters long!' });
      setTimeout(() => setMessage(null), 3000);
      return;
    }

    // Check password complexity requirements
    const hasLowercase = /[a-z]/.test(passwordData.newPassword);
    const hasUppercase = /[A-Z]/.test(passwordData.newPassword);
    const hasNumber = /\d/.test(passwordData.newPassword);

    if (!hasLowercase || !hasUppercase || !hasNumber) {
      setMessage({ 
        type: 'error', 
        text: 'New password must contain at least one lowercase letter, one uppercase letter, and one number!' 
      });
      setTimeout(() => setMessage(null), 3000);
      return;
    }

    if (!passwordData.currentPassword) {
      setMessage({ type: 'error', text: 'Please enter your current password!' });
      setTimeout(() => setMessage(null), 3000);
      return;
    }

    try {
      console.log('🔐 Changing password for authenticated user...');
      
      const response = await authApi.changePassword(
        passwordData.currentPassword,
        passwordData.newPassword
      );
      
      console.log('🔐 Password change response:', response);
      
      if (response.status === 'success') {
        setMessage({ type: 'success', text: 'Password changed successfully!' });
        setPasswordData({ currentPassword: '', newPassword: '', confirmPassword: '' });
        setTimeout(() => setMessage(null), 3000);
      } else {
        throw new Error(response.message || 'Failed to change password');
      }
    } catch (error: any) {
      console.error('❌ Failed to change password:', error);
      
      // Handle validation errors specifically
      if (error.message && error.message.includes('Validation failed')) {
        setMessage({ 
          type: 'error', 
          text: 'Password does not meet requirements. Must contain lowercase, uppercase, and number.' 
        });
      } else {
        setMessage({ 
          type: 'error', 
          text: error.message || 'Failed to change password. Please try again.' 
        });
      }
      setTimeout(() => setMessage(null), 3000);
    }
  };

  const handleNotificationChange = (key: string, value: boolean) => {
    setNotifications(prev => ({ ...prev, [key]: value }));
  };

  const handlePrivacyChange = (key: string, value: boolean) => {
    setPrivacy(prev => ({ ...prev, [key]: value }));
  };

  const handlePreferenceChange = (key: string, value: string) => {
    setPreferences(prev => ({ ...prev, [key]: value }));
  };


  // Role management functions
  const handleCreateRole = async (roleData: any) => {
    try {
      // Validate role data
      if (!roleData.name || !roleData.description) {
        setMessage({ type: 'error', text: 'Validation failed: Role name and description are required' });
        setTimeout(() => setMessage(null), 5000);
        return;
      }

      // Check duplicate role name within current user's organization
      const existingRole = roles.find(r => r.name === roleData.name && (!user?.organization_id || r.organization_id === user.organization_id));
      if (existingRole) {
        setMessage({ type: 'error', text: 'Validation failed: Role name already exists' });
        setTimeout(() => setMessage(null), 5000);
        return;
      }

      const response = await roleApi.createRole(roleData);
      
      if (response.status === 'success') {
        // Refresh roles list
        const rolesResponse = await roleApi.getRolesWithPermissions();
        if (rolesResponse.status === 'success' && rolesResponse.data) {
          setRoles(rolesResponse.data.roles || []);
        }
        setMessage({ type: 'success', text: 'Role created successfully!' });
        setTimeout(() => setMessage(null), 3000);
      } else {
        const errorMessage = response.message || 'Failed to create role';
        if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
          setMessage({ type: 'error', text: `Validation failed: ${errorMessage}` });
        } else {
          setMessage({ type: 'error', text: errorMessage });
        }
        setTimeout(() => setMessage(null), 5000);
      }
    } catch (error: any) {
      console.error('❌ Settings: Error creating role:', error);
      const errorMessage = error.response?.data?.message || error.message || 'Failed to create role';
      if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
        setMessage({ type: 'error', text: `Validation failed: ${errorMessage}` });
      } else {
        setMessage({ type: 'error', text: errorMessage });
      }
      setTimeout(() => setMessage(null), 5000);
    }
  };

  const handleUpdateRole = async (roleId: number, updatedData: any) => {
    try {
      // Validate role data
      if (!updatedData.name || !updatedData.description) {
        setMessage({ type: 'error', text: 'Validation failed: Role name and description are required' });
        setTimeout(() => setMessage(null), 5000);
        return;
      }

      // Check duplicate role name within current user's organization (excluding current role)
      const existingRole = roles.find(r => r.name === updatedData.name && r.id !== roleId && (!user?.organization_id || r.organization_id === user.organization_id));
      if (existingRole) {
        setMessage({ type: 'error', text: 'Validation failed: Role name already exists' });
        setTimeout(() => setMessage(null), 5000);
        return;
      }

      const response = await roleApi.updateRole(roleId, updatedData);
      if (response.status === 'success') {
        // Refresh roles list
        const rolesResponse = await roleApi.getRolesWithPermissions();
        if (rolesResponse.status === 'success' && rolesResponse.data) {
          setRoles(rolesResponse.data.roles || []);
        }
        setMessage({ type: 'success', text: 'Role updated successfully!' });
        setTimeout(() => setMessage(null), 3000);
      } else {
        const errorMessage = response.message || 'Failed to update role';
        if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
          setMessage({ type: 'error', text: `Validation failed: ${errorMessage}` });
        } else {
          setMessage({ type: 'error', text: errorMessage });
        }
        setTimeout(() => setMessage(null), 5000);
      }
    } catch (error: any) {
      console.error('Error updating role:', error);
      const errorMessage = error.response?.data?.message || error.message || 'Failed to update role';
      if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
        setMessage({ type: 'error', text: `Validation failed: ${errorMessage}` });
      } else {
        setMessage({ type: 'error', text: errorMessage });
      }
      setTimeout(() => setMessage(null), 5000);
    }
  };

  const handleDeleteRole = (roleId: number, roleName: string) => {
    setConfirmationDialog({
      isOpen: true,
      title: 'Delete Role',
      message: `Are you sure you want to delete the role "${roleName}"? This action cannot be undone.`,
      onConfirm: () => confirmDeleteRole(roleId),
      isLoading: false
    });
  };

  const confirmDeleteRole = async (roleId: number) => {
    setConfirmationDialog(prev => ({ ...prev, isLoading: true }));
    
    try {
      const response = await roleApi.deleteRole(roleId);
      if (response.status === 'success') {
        // Refresh roles list
        const rolesResponse = await roleApi.getRolesWithPermissions();
        if (rolesResponse.status === 'success' && rolesResponse.data) {
          setRoles(rolesResponse.data.roles || []);
        }
        setMessage({ type: 'success', text: 'Role deleted successfully!' });
        setTimeout(() => setMessage(null), 3000);
        setConfirmationDialog(prev => ({ ...prev, isOpen: false, isLoading: false }));
      } else {
        setMessage({ type: 'error', text: response.message || 'Failed to delete role' });
        setTimeout(() => setMessage(null), 3000);
        setConfirmationDialog(prev => ({ ...prev, isLoading: false }));
      }
    } catch (error) {
      console.error('Error deleting role:', error);
      setMessage({ type: 'error', text: 'Failed to delete role' });
      setTimeout(() => setMessage(null), 3000);
      setConfirmationDialog(prev => ({ ...prev, isLoading: false }));
    }
  };

  // Role modal handlers
  const openRoleModal = (mode: 'create' | 'edit', role?: any) => {
    setRoleModal({
      isOpen: true,
      mode,
      role: role || null
    });
  };

  const closeRoleModal = () => {
    setRoleModal({
      isOpen: false,
      mode: 'create',
      role: null
    });
  };

  const handleRoleSuccess = (roleData: any) => {
    if (roleModal.mode === 'create') {
      handleCreateRole(roleData);
    } else {
      handleUpdateRole(roleData.id, roleData);
    }
  };

  // Permission management functions
  const handleCreatePermission = async (permissionData: any) => {
    try {
      // Validate permission data
      if (!permissionData.name || !permissionData.description || !permissionData.resource || !permissionData.action) {
        setMessage({ type: 'error', text: 'Validation failed: All fields are required (Name, Description, Resource, Action)' });
        setTimeout(() => setMessage(null), 5000);
        return;
      }

      // Check for duplicate permission name
      const existingPermission = permissions.find(p => p.name === permissionData.name);
      if (existingPermission) {
        setMessage({ type: 'error', text: 'Validation failed: Permission name already exists' });
        setTimeout(() => setMessage(null), 5000);
        return;
      }

      const response = await roleApi.createPermission(permissionData);
      
      if (response.status === 'success') {
        // Refresh permissions list
        const permissionsResponse = await roleApi.getPermissions();
        if (permissionsResponse.status === 'success' && permissionsResponse.data) {
          setPermissions(permissionsResponse.data.permissions || []);
        }
        setMessage({ type: 'success', text: 'Permission created successfully!' });
        setTimeout(() => setMessage(null), 3000);
      } else {
        const errorMessage = response.message || 'Failed to create permission';
        if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
          setMessage({ type: 'error', text: `Validation failed: ${errorMessage}` });
        } else {
          setMessage({ type: 'error', text: errorMessage });
        }
        setTimeout(() => setMessage(null), 5000);
      }
    } catch (error: any) {
      console.error('❌ Settings: Error creating permission:', error);
      const errorMessage = error.response?.data?.message || error.message || 'Failed to create permission';
      if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
        setMessage({ type: 'error', text: `Validation failed: ${errorMessage}` });
      } else {
        setMessage({ type: 'error', text: errorMessage });
      }
      setTimeout(() => setMessage(null), 5000);
    }
  };

  const handleUpdatePermission = async (permissionId: number, updatedData: any) => {
    try {
      // Validate permission data
      if (!updatedData.name || !updatedData.description || !updatedData.resource || !updatedData.action) {
        setMessage({ type: 'error', text: 'Validation failed: All fields are required (Name, Description, Resource, Action)' });
        setTimeout(() => setMessage(null), 5000);
        return;
      }

      // Check for duplicate permission name (excluding current permission)
      const existingPermission = permissions.find(p => p.name === updatedData.name && p.id !== permissionId);
      if (existingPermission) {
        setMessage({ type: 'error', text: 'Validation failed: Permission name already exists' });
        setTimeout(() => setMessage(null), 5000);
        return;
      }

      const response = await roleApi.updatePermission(permissionId, updatedData);
      if (response.status === 'success') {
        // Refresh permissions list
        const permissionsResponse = await roleApi.getPermissions();
        if (permissionsResponse.status === 'success' && permissionsResponse.data) {
          setPermissions(permissionsResponse.data.permissions || []);
        }
        setMessage({ type: 'success', text: 'Permission updated successfully!' });
        setTimeout(() => setMessage(null), 3000);
      } else {
        const errorMessage = response.message || 'Failed to update permission';
        if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
          setMessage({ type: 'error', text: `Validation failed: ${errorMessage}` });
        } else {
          setMessage({ type: 'error', text: errorMessage });
        }
        setTimeout(() => setMessage(null), 5000);
      }
    } catch (error: any) {
      console.error('Error updating permission:', error);
      const errorMessage = error.response?.data?.message || error.message || 'Failed to update permission';
      if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
        setMessage({ type: 'error', text: `Validation failed: ${errorMessage}` });
      } else {
        setMessage({ type: 'error', text: errorMessage });
      }
      setTimeout(() => setMessage(null), 5000);
    }
  };

  const handleDeletePermission = (permissionId: number, permissionName: string) => {
    setConfirmationDialog({
      isOpen: true,
      title: 'Delete Permission',
      message: `Are you sure you want to delete the permission "${permissionName}"? This action cannot be undone.`,
      onConfirm: () => confirmDeletePermission(permissionId),
      isLoading: false
    });
  };

  const confirmDeletePermission = async (permissionId: number) => {
    setConfirmationDialog(prev => ({ ...prev, isLoading: true }));
    
    try {
      const response = await roleApi.deletePermission(permissionId);
      if (response.status === 'success') {
        // Refresh permissions list
        const permissionsResponse = await roleApi.getPermissions();
        if (permissionsResponse.status === 'success' && permissionsResponse.data) {
          setPermissions(permissionsResponse.data.permissions || []);
        }
        setMessage({ type: 'success', text: 'Permission deleted successfully!' });
        setTimeout(() => setMessage(null), 3000);
        setConfirmationDialog(prev => ({ ...prev, isOpen: false, isLoading: false }));
      } else {
        setMessage({ type: 'error', text: response.message || 'Failed to delete permission' });
        setTimeout(() => setMessage(null), 3000);
        setConfirmationDialog(prev => ({ ...prev, isLoading: false }));
      }
    } catch (error) {
      console.error('Error deleting permission:', error);
      setMessage({ type: 'error', text: 'Failed to delete permission' });
      setTimeout(() => setMessage(null), 3000);
      setConfirmationDialog(prev => ({ ...prev, isLoading: false }));
    }
  };

  // Permission modal handlers
  const openPermissionModal = (mode: 'create' | 'edit', permission?: any) => {
    setPermissionModal({
      isOpen: true,
      mode,
      permission: permission || null
    });
  };

  const closePermissionModal = () => {
    setPermissionModal({
      isOpen: false,
      mode: 'create',
      permission: null
    });
  };

  const handlePermissionSuccess = (permissionData: any) => {
    if (permissionModal.mode === 'create') {
      handleCreatePermission(permissionData);
    } else {
      handleUpdatePermission(permissionData.id, permissionData);
    }
  };

  // Filter functions for roles and permissions
  const getFilteredRoles = () => {
    if (!roles || !Array.isArray(roles)) {
      return [];
    }
    
    return roles.filter(role => {
      if (!role) return false;
      
      const matchesSearch = roleSearchQuery === '' || 
        (role.name && role.name.toLowerCase().includes(roleSearchQuery.toLowerCase())) ||
        (role.description && role.description.toLowerCase().includes(roleSearchQuery.toLowerCase()));
      
      const matchesLevel = roleFilterLevel === 'all' || 
        (roleFilterLevel === 'high' && role.level >= 50) ||
        (roleFilterLevel === 'medium' && role.level >= 20 && role.level < 50) ||
        (roleFilterLevel === 'low' && role.level < 20);
      
      return matchesSearch && matchesLevel;
    });
  };

  const getFilteredPermissions = () => {
    if (!permissions || !Array.isArray(permissions)) {
      return [];
    }
    
    return permissions.filter(permission => {
      if (!permission) return false;
      
      const matchesSearch = permissionSearchQuery === '' || 
        (permission.name && permission.name.toLowerCase().includes(permissionSearchQuery.toLowerCase())) ||
        (permission.description && permission.description.toLowerCase().includes(permissionSearchQuery.toLowerCase())) ||
        (permission.resource && permission.resource.toLowerCase().includes(permissionSearchQuery.toLowerCase())) ||
        (permission.action && permission.action.toLowerCase().includes(permissionSearchQuery.toLowerCase()));
      
      const matchesResource = permissionFilterResource === 'all' || 
        permission.resource === permissionFilterResource;
      
      return matchesSearch && matchesResource;
    });
  };


  // Get unique resources for filter dropdown
  const getUniqueResources = () => {
    if (!permissions || !Array.isArray(permissions)) {
      return [];
    }
    const resources = [...new Set(permissions.map(p => p?.resource).filter(Boolean))];
    return resources.sort();
  };

  const renderProfileSettings = () => (
    <div className="space-y-6">
      <div className="flex items-center space-x-4">
        <div className="w-20 h-20 bg-blue-600 rounded-full flex items-center justify-center text-white text-2xl font-bold">
          {user?.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-900">{user?.name}</h3>
          <p className="text-gray-600">Captain - CNS</p>
          <p className="text-gray-500 text-sm">Naval Headquarters</p>
          <div className="mt-1">
            <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
              user?.role === 'Super_admin' ? 'bg-red-100 text-red-800' :
              user?.role === 'Admin' ? 'bg-blue-100 text-blue-800' :
              'bg-green-100 text-green-800'
            }`}>
              {user?.role}
            </span>
          </div>
          <button className="mt-2 text-sm text-blue-600 hover:text-blue-800">
            Change Photo
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Full Name
          </label>
          <input
            type="text"
            value={profileData.name}
            onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        {/* Rank dropdown hidden as requested */}
        {/* <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Rank
          </label>
          <select
            value={profileData.rank}
            onChange={(e) => setProfileData(prev => ({ ...prev, rank: e.target.value }))}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="Admiral">Admiral</option>
            <option value="Vice Admiral">Vice Admiral</option>
            <option value="Rear Admiral">Rear Admiral</option>
            <option value="Commodore">Commodore</option>
            <option value="Captain">Captain</option>
            <option value="Commander">Commander</option>
            <option value="Lieutenant Commander">Lieutenant Commander</option>
            <option value="Lieutenant">Lieutenant</option>
            <option value="Sub Lieutenant">Sub Lieutenant</option>
            <option value="Acting Sub Lieutenant">Acting Sub Lieutenant</option>
            <option value="Master Chief Petty Officer">Master Chief Petty Officer</option>
            <option value="Chief Petty Officer">Chief Petty Officer</option>
            <option value="Petty Officer">Petty Officer</option>
            <option value="Leading Seaman">Leading Seaman</option>
            <option value="Seaman">Seaman</option>
          </select>
        </div> */}

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Unit
          </label>
          <input
            type="text"
            value={profileData.unit}
            onChange={(e) => setProfileData(prev => ({ ...prev, unit: e.target.value }))}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            <Mail className="inline h-4 w-4 mr-1" />
            Email
          </label>
          <input
            type="email"
            value={profileData.email}
            onChange={(e) => setProfileData(prev => ({ ...prev, email: e.target.value }))}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            <Phone className="inline h-4 w-4 mr-1" />
            Phone
          </label>
          <input
            type="tel"
            value={profileData.phone}
            onChange={(e) => setProfileData(prev => ({ ...prev, phone: e.target.value }))}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">LOGIN ACCESS</label>
          <div className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-700">LOGIN ACCESS</div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            <MapPin className="inline h-4 w-4 mr-1" />
            Address
          </label>
          <input
            type="text"
            value={profileData.address}
            onChange={(e) => setProfileData(prev => ({ ...prev, address: e.target.value }))}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>
      </div>

      <button
        onClick={handleProfileSave}
        className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
      >
        <Save className="h-4 w-4 mr-2" />
        Save Changes
      </button>
    </div>
  );

  const renderSecuritySettings = () => (
    <div className="space-y-6">
      <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
        <div className="flex items-center">
          <AlertTriangle className="h-5 w-5 text-yellow-600 mr-2" />
          <p className="text-sm text-yellow-800">
            For security reasons, changing your password will log you out of all other devices.
          </p>
        </div>
      </div>

      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Current Password
          </label>
          <div className="relative">
            <input
              type={showCurrentPassword ? 'text' : 'password'}
              value={passwordData.currentPassword}
              onChange={(e) => setPasswordData(prev => ({ ...prev, currentPassword: e.target.value }))}
              className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            <button
              type="button"
              onClick={() => setShowCurrentPassword(!showCurrentPassword)}
              className="absolute right-3 top-2.5 text-gray-400 hover:text-gray-600"
            >
              {showCurrentPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            New Password
          </label>
          <div className="relative">
            <input
              type={showNewPassword ? 'text' : 'password'}
              value={passwordData.newPassword}
              onChange={(e) => setPasswordData(prev => ({ ...prev, newPassword: e.target.value }))}
              className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            <button
              type="button"
              onClick={() => setShowNewPassword(!showNewPassword)}
              className="absolute right-3 top-2.5 text-gray-400 hover:text-gray-600"
            >
              {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>
          <p className="text-xs text-gray-500 mt-1">Must be at least 6 characters long with lowercase, uppercase, and number</p>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Confirm New Password
          </label>
          <div className="relative">
            <input
              type={showConfirmPassword ? 'text' : 'password'}
              value={passwordData.confirmPassword}
              onChange={(e) => setPasswordData(prev => ({ ...prev, confirmPassword: e.target.value }))}
              className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            <button
              type="button"
              onClick={() => setShowConfirmPassword(!showConfirmPassword)}
              className="absolute right-3 top-2.5 text-gray-400 hover:text-gray-600"
            >
              {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>
        </div>
      </div>

      <div className="space-y-4">
        <h4 className="text-lg font-medium text-gray-900">Two-Factor Authentication</h4>
        <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
          <div className="flex items-center">
            <Smartphone className="h-5 w-5 text-gray-600 mr-3" />
            <div>
              <p className="font-medium text-gray-900">LOGIN ACCESS</p>
              <p className="text-sm text-gray-600">LOGIN ACCESS</p>
            </div>
          </div>
        </div>
      </div>

      <button
        onClick={handlePasswordChange}
        className="flex items-center px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
      >
        <Shield className="h-4 w-4 mr-2" />
        Change Password
      </button>
    </div>
  );

  const renderNotificationSettings = () => (
    <div className="space-y-6">
      <div className="space-y-4">
        <h4 className="text-lg font-medium text-gray-900">Communication</h4>
        <div className="space-y-3">
          {[
            { key: 'email', label: 'Email Notifications', description: 'Receive notifications via email' },
            { key: 'push', label: 'Push Notifications', description: 'Receive push notifications in browser' },
            { key: 'sms', label: 'SMS Notifications', description: 'Receive notifications via SMS' }
          ].map((item) => (
            <div key={item.key} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
              <div>
                <p className="font-medium text-gray-900">{item.label}</p>
                <p className="text-sm text-gray-600">{item.description}</p>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={notifications[item.key as keyof typeof notifications]}
                  onChange={(e) => handleNotificationChange(item.key, e.target.checked)}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
              </label>
            </div>
          ))}
        </div>
      </div>

      <div className="space-y-4">
        <h4 className="text-lg font-medium text-gray-900">Alerts</h4>
        <div className="space-y-3">
          {[
            { key: 'securityAlerts', label: 'Security Alerts', description: 'Important security notifications' },
            { key: 'messageNotifications', label: 'Message Notifications', description: 'New message alerts' },
            { key: 'systemUpdates', label: 'System Updates', description: 'System maintenance and updates' }
          ].map((item) => (
            <div key={item.key} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
              <div>
                <p className="font-medium text-gray-900">{item.label}</p>
                <p className="text-sm text-gray-600">{item.description}</p>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={notifications[item.key as keyof typeof notifications]}
                  onChange={(e) => handleNotificationChange(item.key, e.target.checked)}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
              </label>
            </div>
          ))}
        </div>
      </div>
    </div>
  );

  const renderPrivacySettings = () => (
    <div className="space-y-6">
      <div className="space-y-4">
        <h4 className="text-lg font-medium text-gray-900">Visibility</h4>
        <div className="space-y-3">
          {[
            { key: 'showOnlineStatus', label: 'Show Online Status', description: 'Allow others to see when you are online' },
            { key: 'allowDirectMessages', label: 'Allow Direct Messages', description: 'Let others send you direct messages' },
            { key: 'showInDirectory', label: 'Show in Directory', description: 'Make your profile visible in the directory' }
          ].map((item) => (
            <div key={item.key} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
              <div>
                <p className="font-medium text-gray-900">{item.label}</p>
                <p className="text-sm text-gray-600">{item.description}</p>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={privacy[item.key as keyof typeof privacy]}
                  onChange={(e) => handlePrivacyChange(item.key, e.target.checked)}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
              </label>
            </div>
          ))}
        </div>
      </div>

      <div className="space-y-4">
        <h4 className="text-lg font-medium text-gray-900">Data & Privacy</h4>
        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
          <div>
            <p className="font-medium text-gray-900">Data Sharing</p>
            <p className="text-sm text-gray-600">Allow anonymized data to be used for system improvements</p>
          </div>
          <label className="relative inline-flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={privacy.dataSharing}
              onChange={(e) => handlePrivacyChange('dataSharing', e.target.checked)}
              className="sr-only peer"
            />
            <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>
      </div>

      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
        <div className="flex items-center">
          <AlertTriangle className="h-5 w-5 text-red-600 mr-2" />
          <div>
            <p className="font-medium text-red-900">Delete Account</p>
            <p className="text-sm text-red-800">This action cannot be undone. All your data will be permanently deleted.</p>
            <button className="mt-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors">
              Delete Account
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  const renderPreferences = () => (
    <div className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Theme
          </label>
          <select
            value={preferences.theme}
            onChange={(e) => handlePreferenceChange('theme', e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="light">Light</option>
            <option value="dark">Dark</option>
            <option value="auto">Auto (System)</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Language
          </label>
          <select
            value={preferences.language}
            onChange={(e) => handlePreferenceChange('language', e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="en">English</option>
            <option value="bn">বাংলা</option>
            <option value="hi">हिन्दी</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Timezone
          </label>
          <select
            value={preferences.timezone}
            onChange={(e) => handlePreferenceChange('timezone', e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="UTC+6">UTC+6 (Bangladesh Standard Time)</option>
            <option value="UTC+5:30">UTC+5:30 (India Standard Time)</option>
            <option value="UTC+0">UTC+0 (Greenwich Mean Time)</option>
            <option value="UTC-5">UTC-5 (Eastern Standard Time)</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Date Format
          </label>
          <select
            value={preferences.dateFormat}
            onChange={(e) => handlePreferenceChange('dateFormat', e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="DD/MM/YYYY">DD/MM/YYYY</option>
            <option value="MM/DD/YYYY">MM/DD/YYYY</option>
            <option value="YYYY-MM-DD">YYYY-MM-DD</option>
          </select>
        </div>
      </div>

      <div className="space-y-4">
        <h4 className="text-lg font-medium text-gray-900">Accessibility</h4>
        <div className="space-y-3">
          <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
            <div>
              <p className="font-medium text-gray-900">High Contrast Mode</p>
              <p className="text-sm text-gray-600">Increase contrast for better visibility</p>
            </div>
            <label className="relative inline-flex items-center cursor-pointer">
              <input type="checkbox" className="sr-only peer" />
              <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
            </label>
          </div>

          <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
            <div>
              <p className="font-medium text-gray-900">Screen Reader Support</p>
              <p className="text-sm text-gray-600">Optimize for screen readers</p>
            </div>
            <label className="relative inline-flex items-center cursor-pointer">
              <input type="checkbox" className="sr-only peer" />
              <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
            </label>
          </div>
        </div>
      </div>
    </div>
  );

  const renderUserManagementSettings = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h3 className="text-lg font-semibold text-gray-900">User Management</h3>
          <p className="text-sm text-gray-600">Manage user roles and permissions</p>
        </div>
      </div>

      {/* Search and Filter Section */}
      <div className="bg-white shadow-sm rounded-lg p-6">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          {/* Search Input */}
          <div className="relative md:col-span-2">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
            <input
              type="text"
              placeholder="Search users by name, email, unit, or role..."
              value={userSearchQuery}
              onChange={(e) => setUserSearchQuery(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleUserSearch()}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {/* Search Button */}
          <div>
            <button
              onClick={handleUserSearch}
              className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center"
            >
              <Search className="h-4 w-4 mr-2" />
              Search
            </button>
          </div>

          {/* Role Filter */}
          <div className="relative">
            <Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
            <select
              value={userFilterRole}
              onChange={(e) => {
                setUserFilterRole(e.target.value);
                handleUserSearch();
              }}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none bg-white"
            >
              <option value="all">All Roles</option>
              <option value="Super Admin">Super Admin</option>
              {availableRoles.map((role) => (
                <option key={role.id} value={role.name}>
                  {role.name}
                </option>
              ))}
            </select>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
          {/* Status Filter */}
          <div className="relative">
            <Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
            <select
              value={userFilterStatus}
              onChange={(e) => {
                setUserFilterStatus(e.target.value);
                handleUserSearch();
              }}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none bg-white"
            >
              <option value="all">All Status</option>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>

          {/* Users Per Page */}
          <div className="relative">
            <select
              value={usersPagination.usersPerPage}
              onChange={(e) => {
                setUsersPagination(prev => ({ ...prev, usersPerPage: parseInt(e.target.value), currentPage: 1 }));
                handleUserSearch();
              }}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none bg-white"
            >
              <option value={5}>5 per page</option>
              <option value={10}>10 per page</option>
              <option value={25}>25 per page</option>
              <option value={50}>50 per page</option>
            </select>
          </div>
        </div>

        {/* Search Results Count */}
        <div className="mt-4 text-sm text-gray-600">
          Showing {users.length} of {usersPagination.totalUsers} users
          {userSearchQuery && (
            <span className="ml-2 text-blue-600">
              for "{userSearchQuery}"
            </span>
          )}
          {usersLoading && (
            <span className="ml-2 text-blue-600">
              <div className="inline-block animate-spin rounded-full h-3 w-3 border-b-2 border-blue-600"></div>
              Loading...
            </span>
          )}
        </div>
      </div>

      {/* Role-based permissions overview */}
      
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <div className="flex items-center">
            <Shield className="h-8 w-8 text-red-600 mr-3" />
            <div>
              <h4 className="font-semibold text-red-900">Super Admin</h4>
              <p className="text-sm text-red-700">Full system access</p>
            </div>
          </div>
          <div className="mt-3 space-y-1">
            <p className="text-xs text-red-600">• User management</p>
            <p className="text-xs text-red-600">• System settings</p>
            <p className="text-xs text-red-600">• All permissions</p>
          </div>
        </div>

        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
          <div className="flex items-center">
            <SettingsIcon className="h-8 w-8 text-blue-600 mr-3" />
            <div>
              <h4 className="font-semibold text-blue-900">Admin</h4>
              <p className="text-sm text-blue-700">Limited admin access</p>
            </div>
          </div>
          <div className="mt-3 space-y-1">
            <p className="text-xs text-blue-600">• User management</p>
            <p className="text-xs text-blue-600">• Contact management</p>
            <p className="text-xs text-blue-600">• Department management</p>
          </div>
        </div>

        <div className="bg-green-50 border border-green-200 rounded-lg p-4">
          <div className="flex items-center">
            <User className="h-8 w-8 text-green-600 mr-3" />
            <div>
              <h4 className="font-semibold text-green-900">User</h4>
              <p className="text-sm text-green-700">Standard user access</p>
            </div>
          </div>
          <div className="mt-3 space-y-1">
            <p className="text-xs text-green-600">• View contacts</p>
            <p className="text-xs text-green-600">• Send messages</p>
            <p className="text-xs text-green-600">• Basic features</p>
          </div>
        </div>
      </div>

      {/* Users table */}
      <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-200">
          <h4 className="text-lg font-medium text-gray-900">All Users</h4>
          <p className="text-sm text-gray-600">Manage user roles and permissions</p>
        </div>
        
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  USER NAME
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  RANK & UNIT
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  ROLE & DESIGNATION
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  STATUS
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  ACTIONS
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {getFilteredUsers().map((userData) => (
                <tr key={userData.id} className="hover:bg-gray-50 transition-colors">
                  {/* CONTACT */}
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center">
                      <div className="flex-shrink-0 h-10 w-10 rounded-full flex items-center justify-center text-white font-semibold bg-blue-500">
                        {userData.name?.split(' ').map((n: string) => n[0]).join('').slice(0, 2) || 'U'}
                      </div>
                      <div className="ml-4">
                        <div className="text-sm font-medium text-gray-900">{userData.name || 'Unknown User'}</div>
                        <div className="text-sm text-gray-500">{userData.service_no || userData.email || 'No ID'}</div>
                      </div>
                    </div>
                  </td>

                  {/* RANK & UNIT */}
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-900">{userData.rank || 'N/A'}</div>
                    <div className="text-sm text-gray-500">{userData.unit || 'No Unit'}</div>
                  </td>

                  {/* ROLE & DESIGNATION */}
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center space-x-2">
                      <select
                        value={userData.role || 'User'}
                        onChange={(e) => handleUserRoleChange(userData.id, e.target.value)}
                        disabled={
                          userData.id === 1 || // Cannot change Super Admin role
                          userData.role === 'Super Admin' || 
                          userData.role === 'Super_admin' ||
                          userData.id === user?.id // Cannot change own role
                        }
                        className={`text-xs rounded-md border-0 focus:ring-2 focus:ring-blue-500 px-2 py-1 ${
                          userData.role === 'Super Admin' || userData.role === 'Super_admin' ? 'bg-green-100 text-green-800' :
                          userData.role === 'Admin' ? 'bg-blue-100 text-blue-800' :
                          userData.role === 'Manager' ? 'bg-purple-100 text-purple-800' :
                          userData.role === 'Officer' ? 'bg-orange-100 text-orange-800' :
                          userData.role === 'Navy_admin' ? 'bg-indigo-100 text-indigo-800' :
                          'bg-gray-100 text-gray-800'
                        } ${userData.id === 1 || userData.role === 'Super Admin' || userData.role === 'Super_admin' || userData.id === user?.id ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'}`}
                      >
                        {userData.role === 'Super Admin' || userData.role === 'Super_admin' ? (
                          <option value={userData.role}>{userData.role}</option>
                        ) : (
                          availableRoles.map((role) => (
                            <option key={role.id} value={role.name}>
                              {role.name}
                            </option>
                          ))
                        )}
                      </select>
                    </div>
                    <div className="text-sm text-gray-500 mt-1">{userData.designation || 'No Designation'}</div>
                  </td>

                  {/* STATUS */}
                  <td className="px-6 py-4 whitespace-nowrap">
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={userData.is_active}
                        onChange={(e) => handleUserStatusChange(userData.id, e.target.checked)}
                        disabled={
                          userData.id === 1 || // Cannot change Super Admin status
                          userData.role === 'Super Admin' || 
                          userData.role === 'Super_admin' ||
                          userData.id === user?.id // Cannot change own status
                        }
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"></div>
                      <span className="ml-2 text-xs text-gray-600">
                        {userData.is_active ? 'Active' : 'Inactive'}
                      </span>
                    </label>
                  </td>

                  {/* ACTIONS */}
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex items-center space-x-2">
                      <button
                        onClick={() => handleViewUser(userData)}
                        className="text-blue-600 hover:text-blue-900 transition-colors"
                        title="View User Details"
                      >
                        <Eye className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => handleEditUser(userData)}
                        className="text-gray-600 hover:text-gray-900 transition-colors"
                        title="Edit User"
                      >
                        <Edit className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => handleDeleteUser(userData.id, userData.name)}
                        disabled={
                          userData.id === 1 || // Cannot delete Super Admin
                          userData.role === 'Super Admin' || 
                          userData.role === 'Super_admin' ||
                          userData.id === user?.id // Cannot delete yourself
                        }
                        className="text-red-600 hover:text-red-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        title="Delete User"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {usersPagination.totalPages > 1 && (
          <div className="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
            <div className="flex-1 flex justify-between sm:hidden">
              <button
                onClick={() => handleUserPageChange(usersPagination.currentPage - 1)}
                disabled={usersPagination.currentPage === 1}
                className="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Previous
              </button>
              <button
                onClick={() => handleUserPageChange(usersPagination.currentPage + 1)}
                disabled={usersPagination.currentPage === usersPagination.totalPages}
                className="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Next
              </button>
            </div>
            <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
              <div>
                <p className="text-sm text-gray-700">
                  Showing{' '}
                  <span className="font-medium">
                    {(usersPagination.currentPage - 1) * usersPagination.usersPerPage + 1}
                  </span>{' '}
                  to{' '}
                  <span className="font-medium">
                    {Math.min(usersPagination.currentPage * usersPagination.usersPerPage, usersPagination.totalUsers)}
                  </span>{' '}
                  of{' '}
                  <span className="font-medium">{usersPagination.totalUsers}</span>{' '}
                  results
                </p>
              </div>
              <div>
                <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                  <button
                    onClick={() => handleUserPageChange(usersPagination.currentPage - 1)}
                    disabled={usersPagination.currentPage === 1}
                    className="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <span className="sr-only">Previous</span>
                    <svg className="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                      <path fillRule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clipRule="evenodd" />
                    </svg>
                  </button>
                  
                  {/* Page Numbers */}
                  {Array.from({ length: Math.min(5, usersPagination.totalPages) }, (_, i) => {
                    const startPage = Math.max(1, usersPagination.currentPage - 2);
                    const pageNumber = startPage + i;
                    
                    if (pageNumber > usersPagination.totalPages) return null;
                    
                    return (
                      <button
                        key={pageNumber}
                        onClick={() => handleUserPageChange(pageNumber)}
                        className={`relative inline-flex items-center px-4 py-2 border text-sm font-medium ${
                          pageNumber === usersPagination.currentPage
                            ? 'z-10 bg-blue-50 border-blue-500 text-blue-600'
                            : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'
                        }`}
                      >
                        {pageNumber}
                      </button>
                    );
                  })}
                  
                  <button
                    onClick={() => handleUserPageChange(usersPagination.currentPage + 1)}
                    disabled={usersPagination.currentPage === usersPagination.totalPages}
                    className="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <span className="sr-only">Next</span>
                    <svg className="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                      <path fillRule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clipRule="evenodd" />
                    </svg>
                  </button>
                </nav>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );

  const renderRolesSettings = () => {
    if (rolesLoading) {
      return (
        <div className="space-y-6">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-semibold text-gray-900">Role Management</h3>
          </div>
          <div className="bg-white shadow-sm rounded-lg p-8 text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-4 text-gray-600">Loading roles...</p>
          </div>
        </div>
      );
    }

    if (rolesError) {
      return (
        <div className="space-y-6">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-semibold text-gray-900">Role Management</h3>
          </div>
          <div className="bg-red-50 border border-red-200 rounded-lg p-4">
            <div className="flex items-center">
              <AlertTriangle className="h-5 w-5 text-red-600 mr-2" />
              <p className="text-red-800">{rolesError}</p>
            </div>
          </div>
        </div>
      );
    }

    return (
      <div className="space-y-6">
        <div className="flex justify-between items-center">
          <h3 className="text-lg font-semibold text-gray-900">Role Management</h3>
          <PermissionButton
            permission="role.create"
            onClick={() => openRoleModal('create')}
            disabled={permissions.length === 0}
            className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Plus className="h-4 w-4 mr-2" />
            Add Role
          </PermissionButton>
        </div>

        {/* Search and Filter Section */}
        <div className="bg-white shadow-sm rounded-lg p-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Search Input */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
              <input
                type="text"
                placeholder="Search roles by name or description..."
                value={roleSearchQuery}
                onChange={(e) => setRoleSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>

            {/* Level Filter */}
            <div className="relative">
              <Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
              <select
                value={roleFilterLevel}
                onChange={(e) => setRoleFilterLevel(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none bg-white"
              >
                <option value="all">All Levels</option>
                <option value="high">High Level (50+)</option>
                <option value="medium">Medium Level (20-49)</option>
                <option value="low">Low Level (0-19)</option>
              </select>
            </div>
          </div>

          {/* Search Results Count */}
          <div className="mt-4 text-sm text-gray-600">
            Showing {getFilteredRoles().length} of {roles.length} roles
            {roleSearchQuery && (
              <span className="ml-2 text-blue-600">
                for "{roleSearchQuery}"
              </span>
            )}
          </div>
        </div>

        {getFilteredRoles().length === 0 ? (
          <div className="bg-white shadow-sm rounded-lg p-8 text-center">
            <Crown className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <p className="text-gray-600">
              {roleSearchQuery || roleFilterLevel !== 'all' 
                ? 'No roles found matching your search criteria.' 
                : 'No roles found. Create your first role to get started.'}
            </p>
            {(roleSearchQuery || roleFilterLevel !== 'all') && (
              <button
                onClick={() => {
                  setRoleSearchQuery('');
                  setRoleFilterLevel('all');
                }}
                className="mt-4 text-blue-600 hover:text-blue-800 text-sm"
              >
                Clear filters
              </button>
            )}
          </div>
        ) : (
          <div className="bg-white shadow-sm rounded-lg overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Role Name
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Description
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Level
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Permissions
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Actions
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {getFilteredRoles().map((role) => (
              <tr key={role.id} className="hover:bg-gray-50">
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="flex items-center text-sm font-medium text-gray-900">
                    <Crown className="h-4 w-4 mr-2 text-yellow-500" />
                    {role.name}
                  </div>
                </td>
                <td className="px-6 py-4">
                  <div className="text-sm text-gray-500">{role.description}</div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                    role.level >= 100 ? 'bg-red-100 text-red-800' :
                    role.level >= 50 ? 'bg-purple-100 text-purple-800' :
                    role.level >= 30 ? 'bg-blue-100 text-blue-800' :
                    role.level >= 20 ? 'bg-green-100 text-green-800' :
                    'bg-gray-100 text-gray-800'
                  }`}>
                    Level {role.level}
                  </span>
                </td>
                <td className="px-6 py-4">
                  <div className="space-y-1">
                    {!role.permissions || role.permissions.length === 0 ? (
                      <span className="text-sm text-gray-400 italic">No permissions assigned</span>
                    ) : role.permissions.includes('all') ? (
                      <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">
                        All Permissions
                      </span>
                    ) : (
                      <div className="flex flex-wrap gap-1">
                        {role.permissions.slice(0, 3).map((permission: string, index: number) => (
                          <span
                            key={index}
                            className="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800"
                          >
                            {permission}
                          </span>
                        ))}
                        {role.permissions && role.permissions.length > 3 && (
                          <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-600">
                            +{role.permissions.length - 3} more
                          </span>
                        )}
                      </div>
                    )}
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <div className="flex space-x-2">
                    <PermissionButton
                      permission="role.update"
                      onClick={() => openRoleModal('edit', role)}
                      className="text-blue-600 hover:text-blue-900 flex items-center"
                    >
                      <Edit className="h-4 w-4 mr-1" />
                      Edit
                    </PermissionButton>
                    <PermissionButton
                      permission="role.delete"
                      onClick={() => handleDeleteRole(role.id, role.name)}
                      disabled={role.level >= 100} // Cannot delete Super Admin role
                      className="text-red-600 hover:text-red-900 disabled:opacity-50 disabled:cursor-not-allowed flex items-center"
                    >
                      <Trash2 className="h-4 w-4 mr-1" />
                      Delete
                    </PermissionButton>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
          </div>
        )}
      </div>
    );
  };

  const renderPermissionsSettings = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-semibold text-gray-900">Permission Management</h3>
        <PermissionButton
          permission="permission.create"
          onClick={() => openPermissionModal('create')}
          className="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 flex items-center"
        >
          <Plus className="h-4 w-4 mr-2" />
          Add Permission
        </PermissionButton>
      </div>

      {/* Search and Filter Section */}
      <div className="bg-white shadow-sm rounded-lg p-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Search Input */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
            <input
              type="text"
              placeholder="Search permissions by name, description, resource, or action..."
              value={permissionSearchQuery}
              onChange={(e) => setPermissionSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"
            />
          </div>

          {/* Resource Filter */}
          <div className="relative">
            <Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
            <select
              value={permissionFilterResource}
              onChange={(e) => setPermissionFilterResource(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent appearance-none bg-white"
            >
              <option value="all">All Resources</option>
              {getUniqueResources().map(resource => (
                <option key={resource} value={resource}>
                  {resource.charAt(0).toUpperCase() + resource.slice(1).replace('_', ' ')}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Search Results Count */}
        <div className="mt-4 text-sm text-gray-600">
          Showing {getFilteredPermissions().length} of {permissions.length} permissions
          {permissionSearchQuery && (
            <span className="ml-2 text-green-600">
              for "{permissionSearchQuery}"
            </span>
          )}
        </div>
      </div>

      {getFilteredPermissions().length === 0 ? (
        <div className="bg-white shadow-sm rounded-lg p-8 text-center">
          <Key className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <p className="text-gray-600">
            {permissionSearchQuery || permissionFilterResource !== 'all' 
              ? 'No permissions found matching your search criteria.' 
              : 'No permissions found. Create your first permission to get started.'}
          </p>
          {(permissionSearchQuery || permissionFilterResource !== 'all') && (
            <button
              onClick={() => {
                setPermissionSearchQuery('');
                setPermissionFilterResource('all');
              }}
              className="mt-4 text-blue-600 hover:text-blue-800 text-sm"
            >
              Clear filters
            </button>
          )}
        </div>
      ) : (
        <div className="bg-white shadow-sm rounded-lg overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Permission Name
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Description
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Resource
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Action
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Roles
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Actions
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {getFilteredPermissions().map((permission) => (
              <tr key={permission.id} className="hover:bg-gray-50">
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="text-sm font-medium text-gray-900">{permission.name}</div>
                </td>
                <td className="px-6 py-4">
                  <div className="text-sm text-gray-500">{permission.description}</div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">
                    {permission.resource}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">
                    {permission.action}
                  </span>
                </td>
                <td className="px-6 py-4">
                  <div className="space-y-1">
                    {(() => {
                      const rolesWithPermission = roles.filter(role => 
                        (role.permissions && role.permissions.includes(permission.name)) || 
                        (role.permissions && role.permissions.includes('all'))
                      );
                      
                      if (rolesWithPermission.length === 0) {
                        return <span className="text-sm text-gray-400 italic">No roles assigned</span>;
                      }
                      
                      return (
                        <div className="flex flex-wrap gap-1">
                          {rolesWithPermission.slice(0, 3).map((role, index) => (
                            <span
                              key={index}
                              className="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-purple-100 text-purple-800"
                            >
                              {role.name}
                            </span>
                          ))}
                          {rolesWithPermission.length > 3 && (
                            <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-600">
                              +{rolesWithPermission.length - 3} more
                            </span>
                          )}
                        </div>
                      );
                    })()}
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <div className="flex space-x-2">
                    <PermissionButton
                      permission="permission.update"
                      onClick={() => openPermissionModal('edit', permission)}
                      className="text-blue-600 hover:text-blue-900 flex items-center"
                    >
                      <Edit className="h-4 w-4 mr-1" />
                      Edit
                    </PermissionButton>
                    <PermissionButton
                      permission="permission.delete"
                      onClick={() => handleDeletePermission(permission.id, permission.name)}
                      className="text-red-600 hover:text-red-900 flex items-center"
                    >
                      <Trash2 className="h-4 w-4 mr-1" />
                      Delete
                    </PermissionButton>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      )}
    </div>
  );

  return (
    <div className="p-6">
      <div className="mx-auto" style={{ maxWidth: '89rem' }}>
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900">Settings</h1>
          <p className="text-gray-600 mt-2">Manage your account settings and preferences</p>
        </div>

        {message && (
          <div className={`mb-6 p-4 rounded-lg flex items-center ${
            message.type === 'success' 
              ? 'bg-green-50 border border-green-200 text-green-800' 
              : 'bg-red-50 border border-red-200 text-red-800'
          }`}>
            {message.type === 'success' ? (
              <CheckCircle className="h-5 w-5 mr-2" />
            ) : (
              <AlertTriangle className="h-5 w-5 mr-2" />
            )}
            <span className="flex-1">{message.text}</span>
            <button
              onClick={() => setMessage(null)}
              className="ml-2 text-gray-400 hover:text-gray-600"
            >
              <X className="h-4 w-4" />
            </button>
          </div>
        )}

        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          <div className="flex">
            {/* Left Sidebar - Tab Navigation */}
            <div className="w-64 bg-gray-50 border-r border-gray-200">
              <nav className="p-4 space-y-2">
                {tabs.map((tab) => (
                  <button
                    key={tab.id}
                    onClick={() => setActiveTab(tab.id)}
                    className={`w-full flex items-center px-4 py-3 text-sm font-medium rounded-lg transition-colors ${
                      activeTab === tab.id
                        ? 'bg-blue-100 text-blue-700 border border-blue-200'
                        : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
                    }`}
                  >
                    <tab.icon className="h-5 w-5 mr-3" />
                    {tab.label}
                  </button>
                ))}
              </nav>
            </div>

            {/* Right Content Area */}
            <div className="flex-1 p-6" style={{ width: '80%' }}>
              {activeTab === 'profile' && renderProfileSettings()}
              {activeTab === 'security' && renderSecuritySettings()}
              {activeTab === 'notifications' && renderNotificationSettings()}
              {activeTab === 'privacy' && renderPrivacySettings()}
              {activeTab === 'preferences' && renderPreferences()}
              {activeTab === 'roles' && renderRolesSettings()}
              {activeTab === 'permissions' && renderPermissionsSettings()}
              {activeTab === 'users' && renderUserManagementSettings()}
            </div>
          </div>
        </div>
      </div>

      {/* Role Modal */}
      <RoleModal
        isOpen={roleModal.isOpen}
        onClose={closeRoleModal}
        onSuccess={handleRoleSuccess}
        mode={roleModal.mode}
        role={roleModal.role}
        permissions={permissions}
      />

      {/* Permission Modal */}
      <PermissionModal
        isOpen={permissionModal.isOpen}
        onClose={closePermissionModal}
        onSuccess={handlePermissionSuccess}
        mode={permissionModal.mode}
        permission={permissionModal.permission}
        existingPermissions={permissions}
      />

      {/* User Delete Confirmation Dialog */}
      <ConfirmationDialog
        isOpen={isUserDeleteConfirmOpen}
        title="Delete User"
        message={userToDelete ? 
          `Are you sure you want to delete the user "${userToDelete.name}"? This action cannot be undone.` :
          'Are you sure you want to delete this user?'
        }
        confirmText="Delete"
        cancelText="Cancel"
        onConfirm={confirmDeleteUser}
        onClose={cancelDeleteUser}
        type="danger"
      />

      {/* Confirmation Dialog */}
      <ConfirmationDialog
        isOpen={confirmationDialog.isOpen}
        onClose={() => setConfirmationDialog(prev => ({ ...prev, isOpen: false }))}
        onConfirm={confirmationDialog.onConfirm}
        title={confirmationDialog.title}
        message={confirmationDialog.message}
        confirmText="Delete"
        cancelText="Cancel"
        type="danger"
        isLoading={confirmationDialog.isLoading}
      />
    </div>
  );
};

export default Settings;
