import React, { useState, useEffect } from 'react';
import { 
  Users, 
  Shield, 
  FileText, 
  Download,
  Plus,
  Edit,
  Trash2,
  Eye,
  Search,
  AlertTriangle,
  Building2,
  FolderOpen,
  Tag,
  X,
  Globe
} from 'lucide-react';
import { useApp } from '../context/AppContext';
import { useAuth } from '../context/AuthContext';
import ContactDialog from '../components/UI/ContactDialog';
import ConfirmationDialog from '../components/UI/ConfirmationDialog';
import UnitDialog from '../components/UI/UnitDialog';
import DepartmentDialog from '../components/UI/DepartmentDialog';
import DesignationDialog from '../components/UI/DesignationDialog';
import PermissionModal from '../components/UI/PermissionModal';
import CountryDialog from '../components/UI/CountryDialog';
import { contactApi, organizationalApi, departmentsApi, designationsApi, roleApi, countriesApi, locationsApi, Division as ApiDivision, District as ApiDistrict, Thana as ApiThana } from '../services/api';
// Removed mock audit logs import - will use real API data
import { USER_ROLES, User, Unit, Department, Designation } from '../types';
import { Role, Country as ApiCountry } from '../services/api';

const Admin: React.FC = () => {
  const { users, updateUser, deleteUser, fetchContacts } = useApp();
  const { user, hasRole, isSuperAdmin, hasAnyPermission } = useAuth();
  const [activeTab, setActiveTab] = useState<'users' | 'units' | 'locations' | 'departments' | 'designations' | 'permissions' | 'audit' | 'countries'>('users');
  // Safe search query state
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [searchTimeout, setSearchTimeout] = useState<NodeJS.Timeout | null>(null);

  // Safe search query update function
  const updateSearchQuery = (value: string) => {
    try {
      if (typeof value === 'string') {
        setSearchQuery(value);
      } else {
        setSearchQuery('');
      }
    } catch (error) {
      console.error('Error updating search query:', error);
      setSearchQuery('');
    }
  };
  
  // Combined users (API users + mock users for Contact Management)
  const [allUsers, setAllUsers] = useState<User[]>([]);
  
  // New tabs data
  const [units, setUnits] = useState<Unit[]>([]);
  const [departments, setDepartments] = useState<Department[]>([]);
  const [designations, setDesignations] = useState<Designation[]>([]);
  const [countries, setCountries] = useState<ApiCountry[]>([]);
  const [divisions, setDivisions] = useState<ApiDivision[]>([]);
  const [districts, setDistricts] = useState<ApiDistrict[]>([]);
  const [thanas, setThanas] = useState<ApiThana[]>([]);
  
  // Pagination states
  const [unitsPagination, setUnitsPagination] = useState({ currentPage: 1, totalPages: 1, totalItems: 0 });
  const [departmentsPagination, setDepartmentsPagination] = useState({ currentPage: 1, totalPages: 1, totalItems: 0 });
  const [designationsPagination, setDesignationsPagination] = useState({ currentPage: 1, totalPages: 1, totalItems: 0 });
  const [countriesPagination, setCountriesPagination] = useState({ currentPage: 1, totalPages: 1, totalItems: 0 });
  
  // Loading states
  const [unitsLoading, setUnitsLoading] = useState(false);
  const [departmentsLoading, setDepartmentsLoading] = useState(false);
  const [designationsLoading, setDesignationsLoading] = useState(false);
  const [countriesLoading, setCountriesLoading] = useState(false);
  const [divisionsLoading, setDivisionsLoading] = useState(false);
  const [districtsLoading, setDistrictsLoading] = useState(false);
  const [thanasLoading, setThanasLoading] = useState(false);
  
  // Contact dialog states
  const [isContactDialogOpen, setIsContactDialogOpen] = useState(false);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [dialogMode, setDialogMode] = useState<'view' | 'edit'>('view');
  
  // Delete confirmation states
  const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<User | null>(null);
  
  // Role change states
  const [isRoleChangeModalOpen, setIsRoleChangeModalOpen] = useState(false);
  const [userToChangeRole, setUserToChangeRole] = useState<User | null>(null);
  const [newRole, setNewRole] = useState<string>('');
  const [availableRoles, setAvailableRoles] = useState<Role[]>([]);
  const [rolesLoading, setRolesLoading] = useState(false);
  
  // Notification states
  const [notification, setNotification] = useState<{
    type: 'success' | 'error';
    message: string;
    description?: string;
  } | null>(null);

  // Error state
  const [error, setError] = useState<string | null>(null);

  // Audit logs state
  const [auditLogs, setAuditLogs] = useState<any[]>([]);
  const [auditLogsLoading, setAuditLogsLoading] = useState(false);

  // Permissions state
  const [permissions, setPermissions] = useState<any[]>([]);
  const [permissionsLoading, setPermissionsLoading] = useState(false);
  const [permissionsPagination, setPermissionsPagination] = useState({ currentPage: 1, totalPages: 1, totalItems: 0 });

  // CRUD states for Units
  const [isUnitDialogOpen, setIsUnitDialogOpen] = useState(false);
  const [selectedUnit, setSelectedUnit] = useState<Unit | null>(null);
  const [unitDialogMode, setUnitDialogMode] = useState<'add' | 'edit' | 'view'>('add');
  const [unitToDelete, setUnitToDelete] = useState<Unit | null>(null);
  const [isUnitDeleteOpen, setIsUnitDeleteOpen] = useState(false);

  // CRUD states for Departments
  const [isDepartmentDialogOpen, setIsDepartmentDialogOpen] = useState(false);
  const [selectedDepartment, setSelectedDepartment] = useState<Department | null>(null);
  const [departmentDialogMode, setDepartmentDialogMode] = useState<'add' | 'edit' | 'view'>('add');
  const [departmentToDelete, setDepartmentToDelete] = useState<Department | null>(null);
  const [isDepartmentDeleteOpen, setIsDepartmentDeleteOpen] = useState(false);

  // CRUD states for Designations
  const [isDesignationDialogOpen, setIsDesignationDialogOpen] = useState(false);
  const [selectedDesignation, setSelectedDesignation] = useState<Designation | null>(null);
  const [designationDialogMode, setDesignationDialogMode] = useState<'add' | 'edit' | 'view'>('add');
  const [designationToDelete, setDesignationToDelete] = useState<Designation | null>(null);
  const [isDesignationDeleteOpen, setIsDesignationDeleteOpen] = useState(false);
  const [isCountryDialogOpen, setIsCountryDialogOpen] = useState(false);
  const [selectedCountry, setSelectedCountry] = useState<ApiCountry | null>(null);
  const [countryDialogMode, setCountryDialogMode] = useState<'add' | 'edit' | 'view'>('add');
  const [countryToDelete, setCountryToDelete] = useState<ApiCountry | null>(null);
  const [isCountryDeleteOpen, setIsCountryDeleteOpen] = useState(false);
  const [selectedCountryId, setSelectedCountryId] = useState<number | null>(null);
  const [selectedDivisionId, setSelectedDivisionId] = useState<number | null>(null);
  const [selectedDistrictId, setSelectedDistrictId] = useState<number | null>(null);

  // CRUD states for Permissions
  const [isPermissionDialogOpen, setIsPermissionDialogOpen] = useState(false);
  const [selectedPermission, setSelectedPermission] = useState<any | null>(null);
  const [permissionDialogMode, setPermissionDialogMode] = useState<'add' | 'edit' | 'view'>('add');
  const [permissionToDelete, setPermissionToDelete] = useState<any | null>(null);
  const [isPermissionDeleteOpen, setIsPermissionDeleteOpen] = useState(false);

  // Fetch contacts and roles when component mounts
  useEffect(() => {
    const initializeData = async () => {
      try {
        console.log('Admin component mounted, fetching contacts and roles...');
        await Promise.all([
          fetchContacts({ 
            tree: false, 
            limit: 1000, // Increase limit to get all users
            include_inactive: true // Include inactive users for admin view
          }),
          fetchRoles() // Fetch roles for role change functionality
        ]);
      } catch (error) {
        console.error('❌ Error initializing admin data:', error);
        setError('Failed to load admin data. Please refresh the page.');
      }
    };
    
    initializeData();
  }, [fetchContacts]);

  // Use only API users for Contact Management (no mock users)
  useEffect(() => {
    try {
      console.log('Setting users from API only...');
      console.log('API users:', users.length);
      
      // Use only API users - no mock users to avoid ID conflicts
      setAllUsers(users);
      console.log('Set users:', users.length);
    } catch (error) {
      console.error('❌ Error setting users:', error);
      setError('Failed to load user data.');
    }
  }, [users]);

  // Fetch data for new tabs
  const fetchUnits = async (page = 1, search = '') => {
    try {
      console.log('🔍 Fetching units - page:', page, 'search:', search);
      setUnitsLoading(true);
      const response = await organizationalApi.getUnits({ 
        page, 
        limit: 10, 
        search,
        include_inactive: false 
      });
      
      console.log('🔍 Units API response:', response);
      
      if (response.status === 'success' && response.data) {
        console.log('🔍 Units data:', response.data.units);
        // Convert API units to local Unit type
        const convertedUnits = response.data.units.map(u => ({
          ...u,
          is_active: u.is_active === 1
        }));
        setUnits(convertedUnits);
        setUnitsPagination({
          currentPage: response.data.pagination.current_page,
          totalPages: response.data.pagination.total_pages,
          totalItems: response.data.pagination.total_items
        });
      } else {
        console.error('🔍 Failed to fetch units:', response.message);
      }
    } catch (error: any) {
      console.error('❌ Error fetching units:', error);
      setNotification({
        type: 'error',
        message: 'Failed to Load Units',
        description: error.message || 'There was an error loading units. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    } finally {
      setUnitsLoading(false);
    }
  };

  const fetchDepartments = async (page = 1, search = '') => {
    try {
      setDepartmentsLoading(true);
      const response = await departmentsApi.getDepartments({ 
        page, 
        limit: 10, 
        search,
        include_inactive: false 
      });
      
      if (response.status === 'success' && response.data) {
        setDepartments(response.data.departments);
        setDepartmentsPagination({
          currentPage: response.data.pagination.current_page,
          totalPages: response.data.pagination.total_pages,
          totalItems: response.data.pagination.total_items
        });
      }
    } catch (error: any) {
      console.error('❌ Error fetching departments:', error);
      setNotification({
        type: 'error',
        message: 'Failed to Load Departments',
        description: error.message || 'There was an error loading departments. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    } finally {
      setDepartmentsLoading(false);
    }
  };

  const fetchDesignations = async (page = 1, search = '') => {
    try {
      setDesignationsLoading(true);
      const response = await designationsApi.getDesignations({ 
        page, 
        limit: 10, 
        search,
        include_inactive: false 
      });
      
      if (response.status === 'success' && response.data) {
        setDesignations(response.data.designations);
        // Handle pagination if available, otherwise set default values
        if (response.data.pagination) {
          setDesignationsPagination({
            currentPage: response.data.pagination.current_page || 1,
            totalPages: response.data.pagination.total_pages || 1,
            totalItems: response.data.pagination.total_items || response.data.designations.length
          });
        } else {
          // If no pagination data, set default values
          setDesignationsPagination({
            currentPage: 1,
            totalPages: 1,
            totalItems: response.data.designations.length
          });
        }
      }
    } catch (error: any) {
      console.error('❌ Error fetching designations:', error);
      setNotification({
        type: 'error',
        message: 'Failed to Load Designations',
        description: error.message || 'There was an error loading designations. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    } finally {
      setDesignationsLoading(false);
    }
  };

  const fetchCountries = async (page = 1, search = '') => {
    try {
      setCountriesLoading(true);
      const response = await countriesApi.getCountries({
        page,
        limit: 10,
        search,
        include_inactive: false
      });
      if (response.status === 'success' && response.data) {
        setCountries(response.data);
        setCountriesPagination({
          currentPage: page,
          totalPages: 1,
          totalItems: response.data.length
        });
      }
    } catch (error: any) {
      setNotification({
        type: 'error',
        message: 'Failed to Load Countries',
        description: error.message || 'There was an error loading countries. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    } finally {
      setCountriesLoading(false);
    }
  };

  const fetchDivisions = async (countryId?: number) => {
    try {
      setDivisionsLoading(true);
      const response = await locationsApi.getDivisions({
        country_id: typeof countryId === 'number' ? countryId : selectedCountryId || undefined,
        limit: 1000,
        include_inactive: false
      });
      if (response.status === 'success' && response.data) {
        const list = Array.isArray(response.data) ? response.data : [];
        setDivisions(list);
      }
    } catch (error: any) {
      setNotification({
        type: 'error',
        message: 'Failed to Load Divisions',
        description: error.message || 'There was an error loading divisions.'
      });
      setTimeout(() => setNotification(null), 5000);
    } finally {
      setDivisionsLoading(false);
    }
  };

  const fetchDistricts = async (divisionId?: number) => {
    try {
      setDistrictsLoading(true);
      const response = await locationsApi.getDistricts({
        division_id: typeof divisionId === 'number' ? divisionId : selectedDivisionId || undefined,
        limit: 1000,
        include_inactive: false
      });
      if (response.status === 'success' && response.data) {
        const list = Array.isArray((response.data as any)?.districts) ? (response.data as any).districts : response.data;
        setDistricts(list as ApiDistrict[]);
      }
    } catch (error: any) {
      setNotification({
        type: 'error',
        message: 'Failed to Load Districts',
        description: error.message || 'There was an error loading districts.'
      });
      setTimeout(() => setNotification(null), 5000);
    } finally {
      setDistrictsLoading(false);
    }
  };

  const fetchThanas = async (districtId?: number) => {
    try {
      setThanasLoading(true);
      const response = await locationsApi.getThanas({
        district_id: typeof districtId === 'number' ? districtId : selectedDistrictId || undefined,
        limit: 1000,
        include_inactive: false
      });
      if (response.status === 'success' && response.data) {
        const list = Array.isArray((response.data as any)?.thanas) ? (response.data as any).thanas : response.data;
        setThanas(list as ApiThana[]);
      }
    } catch (error: any) {
      setNotification({
        type: 'error',
        message: 'Failed to Load Thanas',
        description: error.message || 'There was an error loading thanas.'
      });
      setTimeout(() => setNotification(null), 5000);
    } finally {
      setThanasLoading(false);
    }
  };

  const fetchPermissions = async (page = 1, search = '') => {
    try {
      setPermissionsLoading(true);
      const response = await roleApi.getPermissions({ 
        page, 
        limit: 10, 
        search,
        include_inactive: false 
      });
      
      if (response.status === 'success' && response.data) {
        setPermissions(response.data.permissions);
        // Handle pagination if available, otherwise set default values
        if (response.data.pagination) {
          setPermissionsPagination({
            currentPage: response.data.pagination.current_page || 1,
            totalPages: response.data.pagination.total_pages || 1,
            totalItems: response.data.pagination.total_items || response.data.permissions.length
          });
        } else {
          // If no pagination data, set default values
          setPermissionsPagination({
            currentPage: 1,
            totalPages: 1,
            totalItems: response.data.permissions.length
          });
        }
      }
    } catch (error: any) {
      console.error('❌ Error fetching permissions:', error);
      setNotification({
        type: 'error',
        message: 'Failed to Load Permissions',
        description: error.message || 'There was an error loading permissions. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    } finally {
      setPermissionsLoading(false);
    }
  };

  // Fetch audit logs with mock data
  const fetchAuditLogs = async () => {
    try {
      setAuditLogsLoading(true);
      
      // Mock audit logs data
      const mockAuditLogs = [
        {
          id: 1,
          userId: 2,
          action: 'LOGIN',
          target: 'System',
          details: 'User logged in successfully',
          timestamp: new Date(Date.now() - 1000 * 60 * 5), // 5 minutes ago
          ipAddress: '192.168.1.100'
        },
        {
          id: 2,
          userId: 2,
          action: 'CREATE',
          target: 'Unit',
          details: 'Created new unit: Naval Headquarters',
          timestamp: new Date(Date.now() - 1000 * 60 * 15), // 15 minutes ago
          ipAddress: '192.168.1.100'
        },
        {
          id: 3,
          userId: 2,
          action: 'UPDATE',
          target: 'Department',
          details: 'Updated department: Operations',
          timestamp: new Date(Date.now() - 1000 * 60 * 30), // 30 minutes ago
          ipAddress: '192.168.1.100'
        },
        {
          id: 4,
          userId: 2,
          action: 'CREATE',
          target: 'Designation',
          details: 'Created new designation: CNS',
          timestamp: new Date(Date.now() - 1000 * 60 * 45), // 45 minutes ago
          ipAddress: '192.168.1.100'
        },
        {
          id: 5,
          userId: 2,
          action: 'DELETE',
          target: 'Contact',
          details: 'Deleted contact: John Doe',
          timestamp: new Date(Date.now() - 1000 * 60 * 60), // 1 hour ago
          ipAddress: '192.168.1.100'
        },
        {
          id: 6,
          userId: 2,
          action: 'EXPORT',
          target: 'Contacts',
          details: 'Exported contacts to CSV',
          timestamp: new Date(Date.now() - 1000 * 60 * 90), // 1.5 hours ago
          ipAddress: '192.168.1.100'
        },
        {
          id: 7,
          userId: 2,
          action: 'UPDATE',
          target: 'User Profile',
          details: 'Updated profile information',
          timestamp: new Date(Date.now() - 1000 * 60 * 120), // 2 hours ago
          ipAddress: '192.168.1.100'
        },
        {
          id: 8,
          userId: 2,
          action: 'PASSWORD_CHANGE',
          target: 'Account',
          details: 'Password changed successfully',
          timestamp: new Date(Date.now() - 1000 * 60 * 180), // 3 hours ago
          ipAddress: '192.168.1.100'
        }
      ];
      
      setAuditLogs(mockAuditLogs);
    } catch (error: any) {
      console.error('❌ Error fetching audit logs:', error);
      setNotification({
        type: 'error',
        message: 'Failed to Load Audit Logs',
        description: error.message || 'There was an error loading audit logs. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    } finally {
      setAuditLogsLoading(false);
    }
  };

  // Load data when switching tabs
  useEffect(() => {
    const loadTabData = async () => {
      try {
        if (activeTab === 'units' && units.length === 0) {
          await fetchUnits();
        } else if (activeTab === 'departments' && departments.length === 0) {
          await fetchDepartments();
        } else if (activeTab === 'designations' && designations.length === 0) {
          await fetchDesignations();
        } else if (activeTab === 'permissions' && permissions.length === 0) {
          await fetchPermissions();
        } else if (activeTab === 'audit' && auditLogs.length === 0) {
          await fetchAuditLogs();
        } else if (activeTab === 'countries' && countries.length === 0) {
          await fetchCountries();
        } else if (activeTab === 'locations' && countries.length === 0) {
          await fetchCountries();
        }
      } catch (error) {
        console.error('❌ Error loading tab data:', error);
        setError(`Failed to load ${activeTab} data.`);
      }
    };
    
    loadTabData();
  }, [activeTab]);

  // Cleanup search timeout on unmount
  useEffect(() => {
    return () => {
      if (searchTimeout) {
        clearTimeout(searchTimeout);
      }
    };
  }, [searchTimeout]);

  // Check if user has admin access using permissions
  if (!isSuperAdmin() && !hasAnyPermission(['admin.access', 'management.access', 'system.admin'])) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-50">
        <div className="text-center p-8 bg-white rounded-lg shadow-lg max-w-md">
          <AlertTriangle className="h-16 w-16 text-red-500 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-900 mb-2">Access Denied</h2>
          <p className="text-gray-600 mb-4">
            You don't have permission to access the Admin panel. This area requires admin permissions.
          </p>
          <p className="text-sm text-gray-500">
            Required permissions: admin.access, management.access, or system.admin
          </p>
        </div>
      </div>
    );
  }

  // Show error if there's an error
  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-50">
        <div className="text-center p-8 bg-white rounded-lg shadow-lg max-w-md">
          <AlertTriangle className="h-16 w-16 text-red-500 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-900 mb-2">Error Loading Admin Panel</h2>
          <p className="text-gray-600 mb-4">{error}</p>
          <button
            onClick={() => window.location.reload()}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            Refresh Page
          </button>
        </div>
      </div>
    );
  }

  const tabs = [
    { id: 'users' as const, label: 'Contact Management', icon: Users },
    { id: 'units' as const, label: 'Unit Management', icon: Building2 },
    { id: 'locations' as const, label: 'Country/Division/District/Thana', icon: Globe },
    { id: 'countries' as const, label: 'Country Management', icon: Globe },
    { id: 'departments' as const, label: 'Department Management', icon: FolderOpen },
    { id: 'designations' as const, label: 'Designation Management', icon: Tag },
    { id: 'permissions' as const, label: 'Permission Management', icon: Shield },
    { id: 'audit' as const, label: 'Audit Logs', icon: FileText }
  ];

  const filteredUsers = React.useMemo(() => {
    try {
      if (!Array.isArray(allUsers) || !searchQuery) {
        return allUsers || [];
      }
      
      const searchLower = (searchQuery || '').toLowerCase();
      return (allUsers || []).filter(user => {
        try {
          if (!user || typeof user !== 'object') return false;
          
          return (
            (user.name && typeof user.name === 'string' && user.name.toLowerCase().includes(searchLower)) ||
            (user.rank && typeof user.rank === 'string' && user.rank.toLowerCase().includes(searchLower)) ||
            (user.unit && typeof user.unit === 'string' && user.unit.toLowerCase().includes(searchLower)) ||
            (user.designation && typeof user.designation === 'string' && user.designation.toLowerCase().includes(searchLower)) ||
            (user.department && typeof user.department === 'string' && user.department.toLowerCase().includes(searchLower)) ||
            (user.service_no && typeof user.service_no === 'string' && user.service_no.toLowerCase().includes(searchLower)) ||
            (user.email && typeof user.email === 'string' && user.email.toLowerCase().includes(searchLower)) ||
            (user.phone && typeof user.phone === 'string' && user.phone.toLowerCase().includes(searchLower)) ||
            (user.role && typeof user.role === 'string' && user.role.toLowerCase().includes(searchLower))
          );
        } catch (error) {
          console.error('Error filtering individual user:', error);
          return false;
        }
      });
    } catch (error) {
      console.error('Error filtering users:', error);
      return allUsers || [];
    }
  }, [allUsers, searchQuery]);

  const filteredUnits = React.useMemo(() => {
    try {
      if (!Array.isArray(units) || !searchQuery) {
        return units || [];
      }
      
      const searchLower = (searchQuery || '').toLowerCase();
      return (units || []).filter(unit => {
        try {
          if (!unit || typeof unit !== 'object') return false;
          
          return (
            (unit.name && typeof unit.name === 'string' && unit.name.toLowerCase().includes(searchLower)) ||
            (unit.code && typeof unit.code === 'string' && unit.code.toLowerCase().includes(searchLower)) ||
            (unit.description && typeof unit.description === 'string' && unit.description.toLowerCase().includes(searchLower)) ||
            (unit.parent_name && typeof unit.parent_name === 'string' && unit.parent_name.toLowerCase().includes(searchLower))
          );
        } catch (error) {
          console.error('Error filtering individual unit:', error);
          return false;
        }
      });
    } catch (error) {
      console.error('Error filtering units:', error);
      return units || [];
    }
  }, [units, searchQuery]);

  const filteredDepartments = React.useMemo(() => {
    try {
      if (!Array.isArray(departments) || !searchQuery) {
        return departments || [];
      }
      
      const searchLower = (searchQuery || '').toLowerCase();
      return (departments || []).filter(department => {
        try {
          if (!department || typeof department !== 'object') return false;
          
          return (
            (department.name && typeof department.name === 'string' && department.name.toLowerCase().includes(searchLower)) ||
            (department.description && typeof department.description === 'string' && department.description.toLowerCase().includes(searchLower)) ||
            (department.parent_name && typeof department.parent_name === 'string' && department.parent_name.toLowerCase().includes(searchLower))
          );
        } catch (error) {
          console.error('Error filtering individual department:', error);
          return false;
        }
      });
    } catch (error) {
      console.error('Error filtering departments:', error);
      return departments || [];
    }
  }, [departments, searchQuery]);

  const filteredDesignations = React.useMemo(() => {
    try {
      if (!Array.isArray(designations) || !searchQuery) {
        return designations || [];
      }
      
      const searchLower = (searchQuery || '').toLowerCase();
      return (designations || []).filter(designation => {
        try {
          if (!designation || typeof designation !== 'object') return false;
          
          return (
            (designation.name && typeof designation.name === 'string' && designation.name.toLowerCase().includes(searchLower)) ||
            (designation.department_name && typeof designation.department_name === 'string' && designation.department_name.toLowerCase().includes(searchLower)) ||
            (designation.description && typeof designation.description === 'string' && designation.description.toLowerCase().includes(searchLower)) ||
            (designation.parent_name && typeof designation.parent_name === 'string' && designation.parent_name.toLowerCase().includes(searchLower))
          );
        } catch (error) {
          console.error('Error filtering individual designation:', error);
          return false;
        }
      });
    } catch (error) {
      console.error('Error filtering designations:', error);
      return designations || [];
    }
  }, [designations, searchQuery]);

  const filteredPermissions = React.useMemo(() => {
    try {
      if (!Array.isArray(permissions) || !searchQuery) {
        return permissions || [];
      }
      
      const searchLower = (searchQuery || '').toLowerCase();
      return (permissions || []).filter(permission => {
        try {
          if (!permission || typeof permission !== 'object') return false;
          
          return (
            (permission.name && typeof permission.name === 'string' && permission.name.toLowerCase().includes(searchLower)) ||
            (permission.description && typeof permission.description === 'string' && permission.description.toLowerCase().includes(searchLower)) ||
            (permission.resource && typeof permission.resource === 'string' && permission.resource.toLowerCase().includes(searchLower)) ||
            (permission.action && typeof permission.action === 'string' && permission.action.toLowerCase().includes(searchLower))
          );
        } catch (error) {
          console.error('Error filtering individual permission:', error);
          return false;
        }
      });
    } catch (error) {
      console.error('Error filtering permissions:', error);
      return permissions || [];
    }
  }, [permissions, searchQuery]);

  const filteredAuditLogs = React.useMemo(() => {
    try {
      if (!Array.isArray(auditLogs) || !searchQuery) {
        return auditLogs || [];
      }
      
      const searchLower = (searchQuery || '').toLowerCase();
      return (auditLogs || []).filter(log => {
        try {
          if (!log || typeof log !== 'object') return false;
          
          const user = users.find(u => u.id === log.userId);
          const userName = user?.name || 'Unknown User';
          
          return (
            (log.action && typeof log.action === 'string' && log.action.toLowerCase().includes(searchLower)) ||
            (log.target && typeof log.target === 'string' && log.target.toLowerCase().includes(searchLower)) ||
            (log.details && typeof log.details === 'string' && log.details.toLowerCase().includes(searchLower)) ||
            (userName && typeof userName === 'string' && userName.toLowerCase().includes(searchLower)) ||
            (log.ipAddress && typeof log.ipAddress === 'string' && log.ipAddress.toLowerCase().includes(searchLower))
          );
        } catch (error) {
          console.error('Error filtering individual audit log:', error);
          return false;
        }
      });
    } catch (error) {
      console.error('Error filtering audit logs:', error);
      return auditLogs || [];
    }
  }, [auditLogs, searchQuery, users]);

  // Contact dialog handlers
  const handleViewContact = (user: User) => {
    setSelectedUser(user);
    setDialogMode('view');
    setIsContactDialogOpen(true);
  };

  const handleEditContact = (user: User) => {
    setSelectedUser(user);
    setDialogMode('edit');
    setIsContactDialogOpen(true);
  };

  const handleDeleteContact = (user: User) => {
    setUserToDelete(user);
    setIsDeleteConfirmOpen(true);
  };

  // Fetch roles from database
  const fetchRoles = async () => {
    try {
      setRolesLoading(true);
      const response = await roleApi.getRoles();
      
      if (response.status === 'success' && response.data) {
        // Filter out Super Admin role and only get active roles
        const filteredRoles = response.data.roles.filter(role => 
          role.name.toLowerCase() !== 'super admin' && role.is_active
        );
        setAvailableRoles(filteredRoles);
        console.log('Available roles loaded:', filteredRoles);
      } else {
        console.error('Failed to fetch roles:', response.message);
      }
    } catch (error) {
      console.error('Error fetching roles:', error);
    } finally {
      setRolesLoading(false);
    }
  };

  // Role change handlers
  const handleChangeRole = (user: User) => {
    // Check permissions - only Super Admin or users with role management permission can change roles
    if (!isSuperAdmin() && !hasAnyPermission(['role.manage', 'user.role.change', 'admin.role.manage'])) {
      setNotification({
        type: 'error',
        message: 'Permission Denied',
        description: 'You do not have permission to change user roles.'
      });
      setTimeout(() => setNotification(null), 5000);
      return;
    }
    
    // Fetch roles if not already loaded
    if (availableRoles.length === 0) {
      fetchRoles();
    }
    
    setUserToChangeRole(user);
    setNewRole(user.role);
    setIsRoleChangeModalOpen(true);
  };

  const confirmRoleChange = async () => {
    if (!userToChangeRole || !newRole) return;
    
    try {
      // Update user role via API
      const response = await contactApi.updateContact(userToChangeRole.id, {
        role: newRole
      });
      
      if (response.status === 'success') {
        // Update local state
        updateUser(userToChangeRole.id, { role: newRole });
        
        setNotification({
          type: 'success',
          message: 'Role Updated Successfully!',
          description: `${userToChangeRole.name}'s role has been changed to ${newRole}.`
        });
        
        // Refresh contacts to get updated data
        await fetchContacts({
          tree: false,
          limit: 1000,
          include_inactive: true,
          forceRefresh: true
        });
      } else {
        throw new Error(response.message || 'Failed to update role');
      }
    } catch (error: any) {
      console.error('Failed to change role:', error);
      setNotification({
        type: 'error',
        message: 'Failed to Change Role',
        description: error.message || 'There was an error changing the role. Please try again.'
      });
    } finally {
      setIsRoleChangeModalOpen(false);
      setUserToChangeRole(null);
      setNewRole('');
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const cancelRoleChange = () => {
    setIsRoleChangeModalOpen(false);
    setUserToChangeRole(null);
    setNewRole('');
  };

  const confirmDeleteContact = async () => {
    if (!userToDelete) return;
    
    try {
      // Use the API to delete the contact
      const response = await contactApi.deleteContact(userToDelete.id, { source: 'management' });
      
      if (response.status === 'success') {
        // Update local state
        deleteUser(userToDelete.id);
        
        // Update allUsers state as well
        setAllUsers(prev => prev.filter(user => user.id !== userToDelete.id));
        
        setIsDeleteConfirmOpen(false);
        setUserToDelete(null);
        
        // Show success notification
        setNotification({
          type: 'success',
          message: 'Contact Deleted Successfully!',
          description: `${userToDelete.name} has been removed from the system.`
        });
        
        // Refresh contacts to ensure UI reflects latest data
        await fetchContacts({
          tree: false,
          limit: 1000,
          include_inactive: true,
          forceRefresh: true
        });
        
        // Auto-hide notification after 5 seconds
        setTimeout(() => setNotification(null), 5000);
      } else {
        throw new Error(response.message || 'Failed to delete contact');
      }
    } catch (error) {
      console.error('Failed to delete contact:', error);
      
      // Show error notification
      setNotification({
        type: 'error',
        message: 'Failed to Delete Contact',
        description: 'There was an error deleting the contact. Please try again.'
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const cancelDeleteContact = () => {
    setIsDeleteConfirmOpen(false);
    setUserToDelete(null);
  };

  const handleCloseContactDialog = () => {
    setIsContactDialogOpen(false);
    setSelectedUser(null);
  };

  const handleChangePassword = async (userId: number, newPassword: string) => {
    try {
      console.log('🔐 Changing password for user:', userId, 'Selected user:', selectedUser);
      
      // Use the API to change password
      const response = await contactApi.changePassword(userId, newPassword);
      
      console.log('🔐 Password change response:', response);
      
      if (response.status === 'success') {
        // Show success notification
        setNotification({
          type: 'success',
          message: 'Password Changed Successfully!',
          description: `Password has been updated for ${selectedUser?.name}.`
        });
        
        // Auto-hide notification after 5 seconds
        setTimeout(() => setNotification(null), 5000);
      } else {
        throw new Error(response.message || 'Failed to change password');
      }
    } catch (error) {
      console.error('❌ Failed to change password:', error);
      
      // Show error notification
      setNotification({
        type: 'error',
        message: 'Failed to Change Password',
        description: 'There was an error changing the password. Please try again.'
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    }
  };

  // Unit CRUD handlers
  const handleAddUnit = () => {
    setSelectedUnit(null);
    setUnitDialogMode('add');
    setIsUnitDialogOpen(true);
  };

  const handleViewUnit = (unit: Unit) => {
    setSelectedUnit(unit);
    setUnitDialogMode('view');
    setIsUnitDialogOpen(true);
  };

  const handleEditUnit = (unit: Unit) => {
    setSelectedUnit(unit);
    setUnitDialogMode('edit');
    setIsUnitDialogOpen(true);
  };

  const handleDeleteUnit = (unit: Unit) => {
    setUnitToDelete(unit);
    setIsUnitDeleteOpen(true);
  };

  const confirmDeleteUnit = async () => {
    if (!unitToDelete) return;
    
    try {
      const response = await organizationalApi.deleteUnit(unitToDelete.id);
      
      if (response.status === 'success') {
        // Refresh units data
        await fetchUnits(unitsPagination.currentPage, searchQuery);
        
        setIsUnitDeleteOpen(false);
        setUnitToDelete(null);
        
        setNotification({
          type: 'success',
          message: 'Unit Deleted Successfully!',
          description: `${unitToDelete.name} has been removed from the system.`
        });
        setTimeout(() => setNotification(null), 5000);
      } else {
        throw new Error(response.message || 'Failed to delete unit');
      }
    } catch (error) {
      console.error('Error deleting unit:', error);
      setNotification({
        type: 'error',
        message: 'Failed to Delete Unit',
        description: 'There was an error deleting the unit. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const cancelDeleteUnit = () => {
    setIsUnitDeleteOpen(false);
    setUnitToDelete(null);
  };

  const handleUnitDialogSuccess = async () => {
    // Refresh units data after successful add/edit
    await fetchUnits(unitsPagination.currentPage, searchQuery);
    
    setNotification({
      type: 'success',
      message: 'Unit Operation Successful!',
      description: unitDialogMode === 'add' ? 'Unit has been created successfully.' : 'Unit has been updated successfully.'
    });
    setTimeout(() => setNotification(null), 5000);
  };

  const handleDepartmentDialogSuccess = async () => {
    // Refresh departments data after successful add/edit
    await fetchDepartments(departmentsPagination.currentPage, searchQuery);
    
    setNotification({
      type: 'success',
      message: 'Department Operation Successful!',
      description: departmentDialogMode === 'add' ? 'Department has been created successfully.' : 'Department has been updated successfully.'
    });
    setTimeout(() => setNotification(null), 5000);
  };

  const handleDesignationDialogSuccess = async () => {
    // Refresh designations data after successful add/edit
    await fetchDesignations(designationsPagination.currentPage, searchQuery);
    
    setNotification({
      type: 'success',
      message: 'Designation Operation Successful!',
      description: designationDialogMode === 'add' ? 'Designation has been created successfully.' : 'Designation has been updated successfully.'
    });
    setTimeout(() => setNotification(null), 5000);
  };

  // Department CRUD handlers
  const handleAddDepartment = () => {
    setSelectedDepartment(null);
    setDepartmentDialogMode('add');
    setIsDepartmentDialogOpen(true);
  };

  const handleViewDepartment = (department: Department) => {
    setSelectedDepartment(department);
    setDepartmentDialogMode('view');
    setIsDepartmentDialogOpen(true);
  };

  const handleEditDepartment = (department: Department) => {
    setSelectedDepartment(department);
    setDepartmentDialogMode('edit');
    setIsDepartmentDialogOpen(true);
  };

  const handleDeleteDepartment = (department: Department) => {
    setDepartmentToDelete(department);
    setIsDepartmentDeleteOpen(true);
  };

  const confirmDeleteDepartment = async () => {
    if (!departmentToDelete) return;
    
    try {
      const response = await departmentsApi.deleteDepartment(departmentToDelete.id);
      
      if (response.status === 'success') {
        // Refresh departments data
        await fetchDepartments(departmentsPagination.currentPage, searchQuery);
        
        setIsDepartmentDeleteOpen(false);
        setDepartmentToDelete(null);
        
        setNotification({
          type: 'success',
          message: 'Department Deleted Successfully!',
          description: `${departmentToDelete.name} has been removed from the system.`
        });
        setTimeout(() => setNotification(null), 5000);
      } else {
        throw new Error(response.message || 'Failed to delete department');
      }
    } catch (error) {
      console.error('Error deleting department:', error);
      setNotification({
        type: 'error',
        message: 'Failed to Delete Department',
        description: 'There was an error deleting the department. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const cancelDeleteDepartment = () => {
    setIsDepartmentDeleteOpen(false);
    setDepartmentToDelete(null);
  };

  // Designation CRUD handlers
  const handleAddDesignation = () => {
    setSelectedDesignation(null);
    setDesignationDialogMode('add');
    setIsDesignationDialogOpen(true);
  };

  const handleViewDesignation = (designation: Designation) => {
    setSelectedDesignation(designation);
    setDesignationDialogMode('view');
    setIsDesignationDialogOpen(true);
  };

  const handleEditDesignation = (designation: Designation) => {
    setSelectedDesignation(designation);
    setDesignationDialogMode('edit');
    setIsDesignationDialogOpen(true);
  };

  const handleDeleteDesignation = (designation: Designation) => {
    setDesignationToDelete(designation);
    setIsDesignationDeleteOpen(true);
  };

  const confirmDeleteDesignation = async () => {
    if (!designationToDelete) return;
    
    try {
      const response = await designationsApi.deleteDesignation(designationToDelete.id);
      
      if (response.status === 'success') {
        // Refresh designations data
        await fetchDesignations(designationsPagination.currentPage, searchQuery);
        
        setIsDesignationDeleteOpen(false);
        setDesignationToDelete(null);
        
        setNotification({
          type: 'success',
          message: 'Designation Deleted Successfully!',
          description: `${designationToDelete.name} has been removed from the system.`
        });
        setTimeout(() => setNotification(null), 5000);
      } else {
        throw new Error(response.message || 'Failed to delete designation');
      }
    } catch (error) {
      console.error('Error deleting designation:', error);
      setNotification({
        type: 'error',
        message: 'Failed to Delete Designation',
        description: 'There was an error deleting the designation. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const cancelDeleteDesignation = () => {
    setIsDesignationDeleteOpen(false);
    setDesignationToDelete(null);
  };

  // Permission CRUD handlers
  const handleAddPermission = () => {
    setSelectedPermission(null);
    setPermissionDialogMode('add');
    setIsPermissionDialogOpen(true);
  };

  const handleViewPermission = (permission: any) => {
    setSelectedPermission(permission);
    setPermissionDialogMode('view');
    setIsPermissionDialogOpen(true);
  };

  const handleEditPermission = (permission: any) => {
    setSelectedPermission(permission);
    setPermissionDialogMode('edit');
    setIsPermissionDialogOpen(true);
  };

  const handleDeletePermission = (permission: any) => {
    setPermissionToDelete(permission);
    setIsPermissionDeleteOpen(true);
  };

  const handleAddCountry = () => {
    setSelectedCountry(null);
    setCountryDialogMode('add');
    setIsCountryDialogOpen(true);
  };

  const handleViewCountry = (country: ApiCountry) => {
    setSelectedCountry(country);
    setCountryDialogMode('view');
    setIsCountryDialogOpen(true);
  };

  const handleEditCountry = (country: ApiCountry) => {
    setSelectedCountry(country);
    setCountryDialogMode('edit');
    setIsCountryDialogOpen(true);
  };

  const handleDeleteCountry = (country: ApiCountry) => {
    setCountryToDelete(country);
    setIsCountryDeleteOpen(true);
  };

  const confirmDeleteCountry = async () => {
    if (!countryToDelete) return;
    try {
      const response = await countriesApi.deleteCountry(countryToDelete.id);
      if (response.status === 'success') {
        await fetchCountries(countriesPagination.currentPage, searchQuery);
        setIsCountryDeleteOpen(false);
        setCountryToDelete(null);
        setNotification({
          type: 'success',
          message: 'Country Deleted Successfully!',
          description: `${countryToDelete.name} has been removed from the system.`
        });
        setTimeout(() => setNotification(null), 5000);
      } else {
        throw new Error(response.message || 'Failed to delete country');
      }
    } catch (error) {
      setNotification({
        type: 'error',
        message: 'Failed to Delete Country',
        description: 'There was an error deleting the country. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const cancelDeleteCountry = () => {
    setIsCountryDeleteOpen(false);
    setCountryToDelete(null);
  };

  const handleCountryDialogSuccess = async () => {
    await fetchCountries(countriesPagination.currentPage, searchQuery);
    setNotification({
      type: 'success',
      message: 'Country Operation Successful!',
      description: countryDialogMode === 'add' ? 'Country has been created successfully.' : 'Country has been updated successfully.'
    });
    setTimeout(() => setNotification(null), 5000);
  };

  const handleExportCountries = () => {
    try {
      const headers = ['Name', 'Code', 'Status'];
      const rows = countries.map(c => [
        c.name,
        c.code || '',
        (c.is_active ? 'Active' : 'Inactive')
      ]);
      const csv = [headers, ...rows].map(r => r.map(f => `"${f}"`).join(',')).join('\n');
      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.href = url;
      link.download = `countries_export_${new Date().toISOString().split('T')[0]}.csv`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      setNotification({
        type: 'success',
        message: 'Export Successful!',
        description: `Countries exported successfully. ${countries.length} countries downloaded.`
      });
      setTimeout(() => setNotification(null), 5000);
    } catch (error) {
      setNotification({
        type: 'error',
        message: 'Export Failed',
        description: 'There was an error exporting countries. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const confirmDeletePermission = async () => {
    if (!permissionToDelete) return;
    
    try {
      const response = await roleApi.deletePermission(permissionToDelete.id);
      
      if (response.status === 'success') {
        // Refresh permissions data
        await fetchPermissions(permissionsPagination.currentPage, searchQuery);
        
        setIsPermissionDeleteOpen(false);
        setPermissionToDelete(null);
        
        setNotification({
          type: 'success',
          message: 'Permission Deleted Successfully!',
          description: `${permissionToDelete.name} has been removed from the system.`
        });
        setTimeout(() => setNotification(null), 5000);
      } else {
        throw new Error(response.message || 'Failed to delete permission');
      }
    } catch (error) {
      console.error('Error deleting permission:', error);
      setNotification({
        type: 'error',
        message: 'Failed to Delete Permission',
        description: 'There was an error deleting the permission. Please try again.'
      });
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const cancelDeletePermission = () => {
    setIsPermissionDeleteOpen(false);
    setPermissionToDelete(null);
  };

  const handlePermissionDialogSuccess = async () => {
    // Refresh permissions data after successful add/edit
    await fetchPermissions(permissionsPagination.currentPage, searchQuery);
    
    setNotification({
      type: 'success',
      message: 'Permission Operation Successful!',
      description: permissionDialogMode === 'add' ? 'Permission has been created successfully.' : 'Permission has been updated successfully.'
    });
    setTimeout(() => setNotification(null), 5000);
  };

  // Search handlers with debouncing

  const debouncedSearch = (searchFunction: () => void, delay: number = 500) => {
    if (searchTimeout) {
      clearTimeout(searchTimeout);
    }
    const timeout = setTimeout(searchFunction, delay);
    setSearchTimeout(timeout);
  };

  // Search handler function
  const handleSearch = () => {
    try {
      console.log('🔍 Performing search with query:', searchQuery);
      // The filtering is already handled by the filtered* functions
      // This function can be used for additional search logic if needed
    } catch (error) {
      console.error('Error in search:', error);
    }
  };

  const handleExportContacts = () => {
    try {
      // Create CSV content
      const csvHeaders = ['Name', 'Service No', 'Rank', 'Unit', 'Role', 'Designation', 'Status', 'Email'];
      const csvData = filteredUsers.map(user => [
        user.name,
        user.service_no,
        user.rank,
        user.unit,
        user.role,
        user.designation,
        user.status,
        user.email
      ]);
      
      const csvContent = [csvHeaders, ...csvData]
        .map(row => row.map(field => `"${field}"`).join(','))
        .join('\n');
      
      // Create and download file
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', `contacts_export_${new Date().toISOString().split('T')[0]}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // Show success notification
      setNotification({
        type: 'success',
        message: 'Export Successful!',
        description: `Contacts exported successfully. ${filteredUsers.length} contacts downloaded.`
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    } catch (error) {
      console.error('Export failed:', error);
      
      // Show error notification
      setNotification({
        type: 'error',
        message: 'Export Failed',
        description: 'There was an error exporting contacts. Please try again.'
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const handleExportUnits = () => {
    try {
      // Create CSV content
      const csvHeaders = ['Name', 'Code', 'Description', 'Parent Unit', 'Status', 'Total Users'];
      const csvData = units.map(unit => [
        unit.name,
        unit.code,
        unit.description,
        unit.parent_name || '',
        unit.is_active ? 'Active' : 'Inactive',
        unit.total_users || 0
      ]);
      
      const csvContent = [csvHeaders, ...csvData]
        .map(row => row.map(field => `"${field}"`).join(','))
        .join('\n');
      
      // Create and download file
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', `units_export_${new Date().toISOString().split('T')[0]}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // Show success notification
      setNotification({
        type: 'success',
        message: 'Export Successful!',
        description: `Units exported successfully. ${units.length} units downloaded.`
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    } catch (error) {
      console.error('Export failed:', error);
      
      // Show error notification
      setNotification({
        type: 'error',
        message: 'Export Failed',
        description: 'There was an error exporting units. Please try again.'
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const handleExportDepartments = () => {
    try {
      // Create CSV content
      const csvHeaders = ['Name', 'Description', 'Parent Department', 'Status', 'Total Users'];
      const csvData = departments.map(dept => [
        dept.name,
        dept.description,
        dept.parent_name || '',
        dept.is_active ? 'Active' : 'Inactive',
        dept.total_users || 0
      ]);
      
      const csvContent = [csvHeaders, ...csvData]
        .map(row => row.map(field => `"${field}"`).join(','))
        .join('\n');
      
      // Create and download file
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', `departments_export_${new Date().toISOString().split('T')[0]}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // Show success notification
      setNotification({
        type: 'success',
        message: 'Export Successful!',
        description: `Departments exported successfully. ${departments.length} departments downloaded.`
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    } catch (error) {
      console.error('Export failed:', error);
      
      // Show error notification
      setNotification({
        type: 'error',
        message: 'Export Failed',
        description: 'There was an error exporting departments. Please try again.'
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const handleExportDesignations = () => {
    try {
      // Create CSV content
      const csvHeaders = ['Name', 'Department/Group', 'Description', 'Parent Designation/Position', 'Status'];
      const csvData = designations.map(designation => [
        designation.name,
        designation.department_name || '',
        designation.description,
        designation.parent_name || '',
        designation.is_active ? 'Active' : 'Inactive'
      ]);
      
      const csvContent = [csvHeaders, ...csvData]
        .map(row => row.map(field => `"${field}"`).join(','))
        .join('\n');
      
      // Create and download file
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', `designations_export_${new Date().toISOString().split('T')[0]}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // Show success notification
      setNotification({
        type: 'success',
        message: 'Export Successful!',
        description: `Designations exported successfully. ${designations.length} designations downloaded.`
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    } catch (error) {
      console.error('Export failed:', error);
      
      // Show error notification
      setNotification({
        type: 'error',
        message: 'Export Failed',
        description: 'There was an error exporting designations. Please try again.'
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const handleExportPermissions = () => {
    try {
      // Create CSV content
      const csvHeaders = ['Name', 'Description', 'Resource', 'Action', 'Status'];
      const csvData = permissions.map(permission => [
        permission.name,
        permission.description || '',
        permission.resource || '',
        permission.action || '',
        permission.is_active ? 'Active' : 'Inactive'
      ]);
      
      const csvContent = [csvHeaders, ...csvData]
        .map(row => row.map(field => `"${field}"`).join(','))
        .join('\n');
      
      // Create and download file
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', `permissions_export_${new Date().toISOString().split('T')[0]}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // Show success notification
      setNotification({
        type: 'success',
        message: 'Export Successful!',
        description: `Permissions exported successfully. ${permissions.length} permissions downloaded.`
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    } catch (error) {
      console.error('Export failed:', error);
      
      // Show error notification
      setNotification({
        type: 'error',
        message: 'Export Failed',
        description: 'There was an error exporting permissions. Please try again.'
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const handleUpdateContact = async (contactData: any) => {
    if (!selectedUser) return;
    
    try {
      // Use the API to update the contact
      const response = await contactApi.updateContact(selectedUser.id, contactData);
      
      if (response.status === 'success') {
        // Update local state
        updateUser(selectedUser.id, contactData);
        
        // Update allUsers state as well
        setAllUsers(prev => prev.map(user => 
          user.id === selectedUser.id ? { ...user, ...contactData } : user
        ));
        
        setIsContactDialogOpen(false);
        setSelectedUser(null);
        
        // Show success notification
        setNotification({
          type: 'success',
          message: 'Contact Updated Successfully!',
          description: `${selectedUser.name}'s information has been updated.`
        });
        
        // Refresh contacts to ensure UI reflects latest data
        await fetchContacts({
          tree: false,
          limit: 1000,
          include_inactive: true,
          forceRefresh: true
        });
        
        // Auto-hide notification after 5 seconds
        setTimeout(() => setNotification(null), 5000);
      } else {
        throw new Error(response.message || 'Failed to update contact');
      }
    } catch (error) {
      console.error('Failed to update contact:', error);
      
      // Show error notification
      setNotification({
        type: 'error',
        message: 'Failed to Update Contact',
        description: 'There was an error updating the contact. Please try again.'
      });
      
      // Auto-hide notification after 5 seconds
      setTimeout(() => setNotification(null), 5000);
    }
  };

  const UserManagement = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div className="flex items-center space-x-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search contacts by name, rank, unit, designation..."
              value={searchQuery || ''}
              onChange={(e) => updateSearchQuery(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                }
              }}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-80"
            />
          </div>
          <button
            type="button"
            onClick={handleSearch}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
          >
            <Search className="h-4 w-4 mr-2" />
            Search
          </button>
          {searchQuery && (
            <button
              type="button"
              onClick={() => updateSearchQuery('')}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
        <div className="flex space-x-2">
          <button 
            onClick={handleExportContacts}
            className="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
          >
            <Download className="h-4 w-4 mr-2" />
            Export
          </button>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-200 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">
                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/Position
              </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">
            {filteredUsers.map((user) => (
              <tr key={user.id} className="hover:bg-gray-50">
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="flex items-center">
                    <div className="w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center text-white text-sm font-semibold">
                      {user.name ? user.name.split(' ').map(n => n[0]).join('').slice(0, 2) : 'U'}
                    </div>
                    <div className="ml-4">
                      <div className="text-sm font-medium text-gray-900">{user.name || 'N/A'}</div>
                      <div className="text-sm text-gray-500">{user.service_no || 'N/A'}</div>
                    </div>
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="text-sm text-gray-900">{user.rank || 'N/A'}</div>
                  <div className="text-sm text-gray-500">{user.unit || 'N/A'}</div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="space-y-1">
                    {(isSuperAdmin() || hasAnyPermission(['role.manage', 'user.role.change', 'admin.role.manage'])) ? (
                      <button
                        onClick={() => handleChangeRole(user)}
                        className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full transition-colors hover:opacity-80 ${
                          user.role === USER_ROLES.SUPER_ADMIN ? 'bg-red-100 text-red-800 hover:bg-red-200' :
                          user.role === USER_ROLES.ADMIN ? 'bg-blue-100 text-blue-800 hover:bg-blue-200' :
                          'bg-green-100 text-green-800 hover:bg-green-200'
                        }`}
                        title="Click to change role"
                      >
                        {user.role || 'User'}
                      </button>
                    ) : (
                    <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      user.role === USER_ROLES.SUPER_ADMIN ? 'bg-red-100 text-red-800' :
                      user.role === USER_ROLES.ADMIN ? 'bg-blue-100 text-blue-800' :
                      'bg-green-100 text-green-800'
                    }`}>
                      {user.role || 'User'}
                    </span>
                    )}
                    <div className="text-xs text-gray-500">{user.designation || 'N/A'}</div>
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                    user.status === 'online' ? 'bg-green-100 text-green-800' :
                    user.status === 'busy' ? 'bg-yellow-100 text-yellow-800' :
                    'bg-gray-100 text-gray-800'
                  }`}>
                    {user.status || 'offline'}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <div className="flex space-x-2">
                    <button 
                      onClick={() => handleViewContact(user)}
                      className="text-indigo-600 hover:text-indigo-900 transition-colors"
                      title="View Contact"
                    >
                      <Eye className="h-4 w-4" />
                    </button>
                    <button 
                      onClick={() => handleEditContact(user)}
                      className="text-blue-600 hover:text-blue-900 transition-colors"
                      title="Edit Contact"
                    >
                      <Edit className="h-4 w-4" />
                    </button>
                    {(isSuperAdmin() || hasAnyPermission(['role.manage', 'user.role.change', 'admin.role.manage'])) && (
                      <button 
                        onClick={() => handleChangeRole(user)}
                        className="text-purple-600 hover:text-purple-900 transition-colors"
                        title="Change Role"
                      >
                        <Shield className="h-4 w-4" />
                      </button>
                    )}
                    <button 
                      onClick={() => handleDeleteContact(user)}
                      className="text-red-600 hover:text-red-900 transition-colors"
                      title="Delete Contact"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );

  const RoleManagement = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-semibold text-gray-900">User Role Management</h3>
        {isSuperAdmin() && (
          <button className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
            <Plus className="h-4 w-4 mr-2" />
            Add User Role
          </button>
        )}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {[
          { 
            role: USER_ROLES.SUPER_ADMIN, 
            name: 'Super Admin', 
            description: 'Full system access',
            permissions: ['All System Access', 'User Management', 'Role Management', 'System Settings', 'Audit Logs']
          },
          { 
            role: USER_ROLES.ADMIN, 
            name: 'Admin', 
            description: 'Department/Area management access',
            permissions: ['View All Contacts', 'Manage Department Users', 'Edit Profiles', 'Send Messages', 'View Audit Logs']
          },
          { 
            role: USER_ROLES.USER, 
            name: 'User', 
            description: 'Basic contact access',
            permissions: ['View Contacts', 'Edit Own Profile', 'Send Messages', 'View Directory']
          }
        ].map((roleInfo) => (
          <div key={roleInfo.role} className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div className="flex justify-between items-center mb-4">
              <div>
                <h4 className="text-lg font-medium text-gray-900">{roleInfo.name}</h4>
                <p className="text-sm text-gray-500">{roleInfo.description}</p>
              </div>
              {isSuperAdmin() && (
                <button className="text-blue-600 hover:text-blue-700">
                  <Edit className="h-4 w-4" />
                </button>
              )}
            </div>
            
            <div className="space-y-3">
              {roleInfo.permissions.map((permission) => (
                <div key={permission} className="flex items-center">
                  <div className="w-2 h-2 bg-green-500 rounded-full mr-3"></div>
                  <span className="text-sm text-gray-700">{permission}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* Designation Management */}
      <div className="mt-8">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Designation/Position Management</h3>
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <p className="text-gray-600 mb-4">
            Designations/Positions represent specific positions within the organization hierarchy.
          </p>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {['CNS', 'Secy to CNS', 'Asst. Secy', 'Flag Lt', 'Protocol Offr', 'Escort Offr', 'NS', 'SONA-1', 'Area Commander', 'Deputy Commander'].map((designation) => (
              <div key={designation} className="bg-gray-50 rounded-lg p-3 text-center">
                <span className="text-sm font-medium text-gray-700">{designation}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );

  const AuditLogs = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div className="flex items-center space-x-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search audit logs by action, user, target, details..."
              value={searchQuery || ''}
              onChange={(e) => updateSearchQuery(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                }
              }}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-80"
            />
          </div>
          <button
            type="button"
            onClick={handleSearch}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
          >
            <Search className="h-4 w-4 mr-2" />
            Search
          </button>
          {searchQuery && (
            <button
              type="button"
              onClick={() => updateSearchQuery('')}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
        <button className="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">
          <Download className="h-4 w-4 mr-2" />
          Export Logs
        </button>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-200 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">
                Timestamp
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                User
              </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">
                Target
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Details
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {auditLogsLoading ? (
              <tr>
                <td colSpan={5} className="px-6 py-4 text-center text-gray-500">Loading audit logs...</td>
              </tr>
            ) : filteredAuditLogs.length === 0 ? (
              <tr>
                <td colSpan={5} className="px-6 py-4 text-center text-gray-500">No audit logs found</td>
              </tr>
            ) : (
              filteredAuditLogs.map((log) => {
              const user = users.find(u => u.id === log.userId);
              return (
                <tr key={log.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {new Date(log.timestamp).toLocaleString()}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {user?.name || 'Unknown User'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      log.action === 'LOGIN' ? 'bg-green-100 text-green-800' :
                        log.action === 'DELETE' ? 'bg-red-100 text-red-800' :
                        log.action === 'CREATE' ? 'bg-blue-100 text-blue-800' :
                        log.action === 'UPDATE' ? 'bg-yellow-100 text-yellow-800' :
                        log.action === 'EXPORT' ? 'bg-purple-100 text-purple-800' :
                        log.action === 'PASSWORD_CHANGE' ? 'bg-orange-100 text-orange-800' :
                        'bg-gray-100 text-gray-800'
                    }`}>
                      {log.action}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {log.target || '-'}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-900">
                    {log.details}
                  </td>
                </tr>
              );
              })
            )}
          </tbody>
        </table>
      </div>
    </div>
  );

  // Unit Management Component
  const UnitManagement = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div className="flex items-center space-x-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search units by name, code, description..."
              value={searchQuery || ''}
              onChange={(e) => updateSearchQuery(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                }
              }}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-80"
            />
          </div>
          <button
            type="button"
            onClick={handleSearch}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
          >
            <Search className="h-4 w-4 mr-2" />
            Search
          </button>
          {searchQuery && (
            <button
              type="button"
              onClick={() => updateSearchQuery('')}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
        <div className="flex space-x-2">
          <button 
            onClick={handleAddUnit}
            className="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
          >
            <Plus className="h-4 w-4 mr-2" />
            Add Unit
          </button>
          <button 
            onClick={handleExportUnits}
            className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Download className="h-4 w-4 mr-2" />
            Export
          </button>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-200 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">Name</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Parent Unit</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">
            {unitsLoading ? (
              <tr>
                <td colSpan={4} className="px-6 py-4 text-center text-gray-500">Loading units...</td>
              </tr>
            ) : units.length === 0 ? (
              <tr>
                <td colSpan={4} className="px-6 py-4 text-center text-gray-500">No units found</td>
              </tr>
            ) : (
              filteredUnits.map((unit) => (
                <tr key={unit.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{unit.name}</td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{unit.parent_name || '-'}</td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      unit.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                    }`}>
                      {unit.is_active ? 'Active' : 'Inactive'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex space-x-2">
                      <button 
                        onClick={() => handleViewUnit(unit)}
                        className="text-indigo-600 hover:text-indigo-900"
                        title="View Unit"
                      >
                        <Eye className="h-4 w-4" />
                      </button>
                      <button 
                        onClick={() => handleEditUnit(unit)}
                        className="text-blue-600 hover:text-blue-900"
                        title="Edit Unit"
                      >
                        <Edit className="h-4 w-4" />
                      </button>
                      <button 
                        onClick={() => handleDeleteUnit(unit)}
                        className="text-red-600 hover:text-red-900"
                        title="Delete Unit"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {unitsPagination.totalPages > 1 && (
        <div className="flex items-center justify-between">
          <div className="text-sm text-gray-700">
            Showing {((unitsPagination.currentPage - 1) * 10) + 1} to {Math.min(unitsPagination.currentPage * 10, unitsPagination.totalItems)} of {unitsPagination.totalItems} units
          </div>
          <div className="flex space-x-2">
            <button 
              onClick={() => fetchUnits(unitsPagination.currentPage - 1, searchQuery)}
              disabled={unitsPagination.currentPage === 1}
              className="px-3 py-1 border border-gray-300 rounded-md text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Previous
            </button>
            <span className="px-3 py-1 text-sm">
              Page {unitsPagination.currentPage} of {unitsPagination.totalPages}
            </span>
            <button 
              onClick={() => fetchUnits(unitsPagination.currentPage + 1, searchQuery)}
              disabled={unitsPagination.currentPage === unitsPagination.totalPages}
              className="px-3 py-1 border border-gray-300 rounded-md text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  );

  const LocationManagement = () => (
    <div className="space-y-6">
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
        <h2 className="text-lg font-semibold text-gray-900 mb-3">Location Selector (Country → Division → District → Thana)</h2>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Country</label>
            <select
              value={selectedCountryId ?? ''}
              onChange={async (e) => {
                const val = e.target.value ? parseInt(e.target.value) : null;
                setSelectedCountryId(val);
                setSelectedDivisionId(null);
                setSelectedDistrictId(null);
                setDivisions([]);
                setDistricts([]);
                setThanas([]);
                if (val) await fetchDivisions(val);
              }}
              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="">Select Country</option>
              {countries.map(c => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Division</label>
            <select
              value={selectedDivisionId ?? ''}
              onChange={async (e) => {
                const val = e.target.value ? parseInt(e.target.value) : null;
                setSelectedDivisionId(val);
                setSelectedDistrictId(null);
                setDistricts([]);
                setThanas([]);
                if (val) await fetchDistricts(val);
              }}
              disabled={!selectedCountryId}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
            >
              <option value="">{divisionsLoading ? 'Loading...' : 'Select Division'}</option>
              {divisions.map(d => (
                <option key={d.id} value={d.id}>{d.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">District</label>
            <select
              value={selectedDistrictId ?? ''}
              onChange={async (e) => {
                const val = e.target.value ? parseInt(e.target.value) : null;
                setSelectedDistrictId(val);
                setThanas([]);
                if (val) await fetchThanas(val);
              }}
              disabled={!selectedDivisionId}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
            >
              <option value="">{districtsLoading ? 'Loading...' : 'Select District'}</option>
              {districts.map(d => (
                <option key={d.id} value={d.id}>{d.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Thana</label>
            <select
              value={''}
              disabled={!selectedDistrictId}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
            >
              <option value="">{thanasLoading ? 'Loading...' : 'Select Thana'}</option>
              {thanas.map(t => (
                <option key={t.id} value={t.id}>{t.name}</option>
              ))}
            </select>
          </div>
        </div>
      </div>
    </div>
  );

  const CountryManagement = () => (
    <div className="space-y-6">
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
        <h2 className="text-lg font-semibold text-gray-900 mb-3">Location Selector (Country → Division → District → Thana)</h2>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Country</label>
            <select
              value={selectedCountryId ?? ''}
              onChange={async (e) => {
                const val = e.target.value ? parseInt(e.target.value) : null;
                setSelectedCountryId(val);
                setSelectedDivisionId(null);
                setSelectedDistrictId(null);
                setDivisions([]);
                setDistricts([]);
                setThanas([]);
                if (val) await fetchDivisions(val);
              }}
              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="">Select Country</option>
              {countries.map(c => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Division</label>
            <select
              value={selectedDivisionId ?? ''}
              onChange={async (e) => {
                const val = e.target.value ? parseInt(e.target.value) : null;
                setSelectedDivisionId(val);
                setSelectedDistrictId(null);
                setDistricts([]);
                setThanas([]);
                if (val) await fetchDistricts(val);
              }}
              disabled={!selectedCountryId}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
            >
              <option value="">{divisionsLoading ? 'Loading...' : 'Select Division'}</option>
              {divisions.map(d => (
                <option key={d.id} value={d.id}>{d.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">District</label>
            <select
              value={selectedDistrictId ?? ''}
              onChange={async (e) => {
                const val = e.target.value ? parseInt(e.target.value) : null;
                setSelectedDistrictId(val);
                setThanas([]);
                if (val) await fetchThanas(val);
              }}
              disabled={!selectedDivisionId}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
            >
              <option value="">{districtsLoading ? 'Loading...' : 'Select District'}</option>
              {districts.map(d => (
                <option key={d.id} value={d.id}>{d.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Thana</label>
            <select
              value={''}
              disabled={!selectedDistrictId}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
            >
              <option value="">{thanasLoading ? 'Loading...' : 'Select Thana'}</option>
              {thanas.map(t => (
                <option key={t.id} value={t.id}>{t.name}</option>
              ))}
            </select>
          </div>
        </div>
      </div>
      <div className="flex justify-between items-center">
        <div className="flex items-center space-x-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search countries by name, code..."
              value={searchQuery || ''}
              onChange={(e) => updateSearchQuery(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                }
              }}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-80"
            />
          </div>
          <button
            type="button"
            onClick={handleSearch}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
          >
            <Search className="h-4 w-4 mr-2" />
            Search
          </button>
          {searchQuery && (
            <button
              type="button"
              onClick={() => updateSearchQuery('')}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
        <div className="flex space-x-2">
          <button 
            onClick={handleAddCountry}
            className="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
          >
            <Plus className="h-4 w-4 mr-2" />
            Add Country
          </button>
          <button 
            onClick={handleExportCountries}
            className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Download className="h-4 w-4 mr-2" />
            Export
          </button>
        </div>
      </div>
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 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">Name</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Code</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">
            {countriesLoading ? (
              <tr>
                <td colSpan={4} className="px-6 py-4 text-center text-gray-500">Loading countries...</td>
              </tr>
            ) : countries.length === 0 ? (
              <tr>
                <td colSpan={4} className="px-6 py-4 text-center text-gray-500">No countries found</td>
              </tr>
            ) : (
              countries
                .filter(c => {
                  if (!searchQuery) return true;
                  const q = (searchQuery || '').toLowerCase();
                  return (c.name || '').toLowerCase().includes(q) || (c.code || '').toLowerCase().includes(q);
                })
                .map((country) => (
                  <tr key={country.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{country.name}</td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{country.code || '-'}</td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                        country.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                      }`}>
                        {country.is_active ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                      <div className="flex space-x-2">
                        <button 
                          onClick={() => handleViewCountry(country)}
                          className="text-indigo-600 hover:text-indigo-900 transition-colors"
                          title="View Country"
                        >
                          <Eye className="h-4 w-4" />
                        </button>
                        <button 
                          onClick={() => handleEditCountry(country)}
                          className="text-blue-600 hover:text-blue-900 transition-colors"
                          title="Edit Country"
                        >
                          <Edit className="h-4 w-4" />
                        </button>
                        <button 
                          onClick={() => handleDeleteCountry(country)}
                          className="text-red-600 hover:text-red-900 transition-colors"
                          title="Delete Country"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );

  // Department Management Component
  const DepartmentManagement = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div className="flex items-center space-x-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search departments by name, unit, description..."
              value={searchQuery || ''}
              onChange={(e) => updateSearchQuery(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                }
              }}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-80"
            />
          </div>
          <button
            type="button"
            onClick={handleSearch}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
          >
            <Search className="h-4 w-4 mr-2" />
            Search
          </button>
          {searchQuery && (
            <button
              type="button"
              onClick={() => updateSearchQuery('')}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
        <div className="flex space-x-2">
          <button 
            onClick={handleAddDepartment}
            className="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
          >
            <Plus className="h-4 w-4 mr-2" />
            Add Department/Group
          </button>
          <button 
            onClick={handleExportDepartments}
            className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Download className="h-4 w-4 mr-2" />
            Export
          </button>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-200 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">Name</th>
              
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Parent Department/Group</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Users</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">
            {departmentsLoading ? (
              <tr>
                <td colSpan={6} className="px-6 py-4 text-center text-gray-500">Loading departments...</td>
              </tr>
            ) : departments.length === 0 ? (
              <tr>
                <td colSpan={6} className="px-6 py-4 text-center text-gray-500">No departments found</td>
              </tr>
            ) : (
              filteredDepartments.map((department) => (
                <tr key={department.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{department.name}</td>
                  
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{department.parent_name || '-'}</td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{department.total_users || 0}</td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      department.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                    }`}>
                      {department.is_active ? 'Active' : 'Inactive'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex space-x-2">
                      <button 
                        onClick={() => handleViewDepartment(department)}
                        className="text-indigo-600 hover:text-indigo-900"
                        title="View Department"
                      >
                        <Eye className="h-4 w-4" />
                      </button>
                      <button 
                        onClick={() => handleEditDepartment(department)}
                        className="text-blue-600 hover:text-blue-900"
                        title="Edit Department"
                      >
                        <Edit className="h-4 w-4" />
                      </button>
                      <button 
                        onClick={() => handleDeleteDepartment(department)}
                        className="text-red-600 hover:text-red-900"
                        title="Delete Department"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {departmentsPagination.totalPages > 1 && (
        <div className="flex items-center justify-between">
          <div className="text-sm text-gray-700">
            Showing {((departmentsPagination.currentPage - 1) * 10) + 1} to {Math.min(departmentsPagination.currentPage * 10, departmentsPagination.totalItems)} of {departmentsPagination.totalItems} departments
          </div>
          <div className="flex space-x-2">
            <button 
              onClick={() => fetchDepartments(departmentsPagination.currentPage - 1, searchQuery)}
              disabled={departmentsPagination.currentPage === 1}
              className="px-3 py-1 border border-gray-300 rounded-md text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Previous
            </button>
            <span className="px-3 py-1 text-sm">
              Page {departmentsPagination.currentPage} of {departmentsPagination.totalPages}
            </span>
            <button 
              onClick={() => fetchDepartments(departmentsPagination.currentPage + 1, searchQuery)}
              disabled={departmentsPagination.currentPage === departmentsPagination.totalPages}
              className="px-3 py-1 border border-gray-300 rounded-md text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  );

  // Designation Management Component
  const DesignationManagement = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div className="flex items-center space-x-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search designations/positions by name, department/group, description..."
              value={searchQuery || ''}
              onChange={(e) => updateSearchQuery(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                }
              }}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-80"
            />
          </div>
          <button
            type="button"
            onClick={handleSearch}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
          >
            <Search className="h-4 w-4 mr-2" />
            Search
          </button>
          {searchQuery && (
            <button
              type="button"
              onClick={() => updateSearchQuery('')}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
        <div className="flex space-x-2">
          <button 
            onClick={handleAddDesignation}
            className="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
          >
            <Plus className="h-4 w-4 mr-2" />
            Add Designation/Position
          </button>
          <button 
            onClick={handleExportDesignations}
            className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Download className="h-4 w-4 mr-2" />
            Export
          </button>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-200 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">Name</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Department/Group</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Parent Designation/Position</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">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">
            {designationsLoading ? (
              <tr>
                <td colSpan={6} className="px-6 py-4 text-center text-gray-500">Loading designations...</td>
              </tr>
            ) : designations.length === 0 ? (
              <tr>
                <td colSpan={6} className="px-6 py-4 text-center text-gray-500">No designations found</td>
              </tr>
            ) : (
              filteredDesignations.map((designation) => (
                <tr key={designation.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{designation.name}</td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{designation.department_name || '-'}</td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{designation.parent_name || '-'}</td>
                  <td className="px-6 py-4 text-sm text-gray-500 max-w-xs truncate">{designation.description || '-'}</td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      designation.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                    }`}>
                      {designation.is_active ? 'Active' : 'Inactive'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex space-x-2">
                      <button 
                        onClick={() => handleViewDesignation(designation)}
                        className="text-indigo-600 hover:text-indigo-900"
                        title="View Designation"
                      >
                        <Eye className="h-4 w-4" />
                      </button>
                      <button 
                        onClick={() => handleEditDesignation(designation)}
                        className="text-blue-600 hover:text-blue-900"
                        title="Edit Designation"
                      >
                        <Edit className="h-4 w-4" />
                      </button>
                      <button 
                        onClick={() => handleDeleteDesignation(designation)}
                        className="text-red-600 hover:text-red-900"
                        title="Delete Designation"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {designationsPagination.totalPages > 1 && (
        <div className="flex items-center justify-between">
          <div className="text-sm text-gray-700">
            Showing {((designationsPagination.currentPage - 1) * 10) + 1} to {Math.min(designationsPagination.currentPage * 10, designationsPagination.totalItems)} of {designationsPagination.totalItems} designations
          </div>
          <div className="flex space-x-2">
            <button 
              onClick={() => fetchDesignations(designationsPagination.currentPage - 1, searchQuery)}
              disabled={designationsPagination.currentPage === 1}
              className="px-3 py-1 border border-gray-300 rounded-md text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Previous
            </button>
            <span className="px-3 py-1 text-sm">
              Page {designationsPagination.currentPage} of {designationsPagination.totalPages}
            </span>
            <button 
              onClick={() => fetchDesignations(designationsPagination.currentPage + 1, searchQuery)}
              disabled={designationsPagination.currentPage === designationsPagination.totalPages}
              className="px-3 py-1 border border-gray-300 rounded-md text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  );

  // Permission Management Component
  const PermissionManagement = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div className="flex items-center space-x-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search permissions by name, description, resource, action..."
              value={searchQuery || ''}
              onChange={(e) => updateSearchQuery(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                }
              }}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-80"
            />
          </div>
          <button
            type="button"
            onClick={handleSearch}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
          >
            <Search className="h-4 w-4 mr-2" />
            Search
          </button>
          {searchQuery && (
            <button
              type="button"
              onClick={() => updateSearchQuery('')}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
        <div className="flex space-x-2">
          <button 
            onClick={handleAddPermission}
            className="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
          >
            <Plus className="h-4 w-4 mr-2" />
            Add Permission
          </button>
          <button 
            onClick={handleExportPermissions}
            className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Download className="h-4 w-4 mr-2" />
            Export
          </button>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-200 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">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">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">
            {permissionsLoading ? (
              <tr>
                <td colSpan={6} className="px-6 py-4 text-center text-gray-500">Loading permissions...</td>
              </tr>
            ) : permissions.length === 0 ? (
              <tr>
                <td colSpan={6} className="px-6 py-4 text-center text-gray-500">No permissions found</td>
              </tr>
            ) : (
              filteredPermissions.map((permission) => (
                <tr key={permission.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{permission.name}</td>
                  <td className="px-6 py-4 text-sm text-gray-500 max-w-xs truncate">{permission.description || '-'}</td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{permission.resource || '-'}</td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{permission.action || '-'}</td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      permission.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                    }`}>
                      {permission.is_active ? 'Active' : 'Inactive'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex space-x-2">
                      <button 
                        onClick={() => handleViewPermission(permission)}
                        className="text-indigo-600 hover:text-indigo-900"
                        title="View Permission"
                      >
                        <Eye className="h-4 w-4" />
                      </button>
                      <button 
                        onClick={() => handleEditPermission(permission)}
                        className="text-blue-600 hover:text-blue-900"
                        title="Edit Permission"
                      >
                        <Edit className="h-4 w-4" />
                      </button>
                      <button 
                        onClick={() => handleDeletePermission(permission)}
                        className="text-red-600 hover:text-red-900"
                        title="Delete Permission"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {permissionsPagination.totalPages > 1 && (
        <div className="flex items-center justify-between">
          <div className="text-sm text-gray-700">
            Showing {((permissionsPagination.currentPage - 1) * 10) + 1} to {Math.min(permissionsPagination.currentPage * 10, permissionsPagination.totalItems)} of {permissionsPagination.totalItems} permissions
          </div>
          <div className="flex space-x-2">
            <button 
              onClick={() => fetchPermissions(permissionsPagination.currentPage - 1, searchQuery)}
              disabled={permissionsPagination.currentPage === 1}
              className="px-3 py-1 border border-gray-300 rounded-md text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Previous
            </button>
            <span className="px-3 py-1 text-sm">
              Page {permissionsPagination.currentPage} of {permissionsPagination.totalPages}
            </span>
            <button 
              onClick={() => fetchPermissions(permissionsPagination.currentPage + 1, searchQuery)}
              disabled={permissionsPagination.currentPage === permissionsPagination.totalPages}
              className="px-3 py-1 border border-gray-300 rounded-md text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  );

  return (
    <div className="p-6 space-y-6">
      <h1 className="text-3xl font-bold text-gray-900">Management</h1>

      {/* Tabs */}
      <div className="border-b border-gray-200">
        <nav className="flex space-x-8">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center py-2 px-1 border-b-2 font-medium text-sm transition-colors ${
                activeTab === tab.id
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              <tab.icon className="h-5 w-5 mr-2" />
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab Content */}
      <div>
        {activeTab === 'users' && (isSuperAdmin() || hasAnyPermission(['contact.read', 'contact.manage', 'user.manage'])) && <UserManagement />}
        {activeTab === 'units' && (isSuperAdmin() || hasAnyPermission(['unit.read', 'unit.manage', 'organization.manage'])) && <UnitManagement />}
        {activeTab === 'locations' && (isSuperAdmin() || hasAnyPermission(['location.read', 'location.manage', 'country.manage'])) && <LocationManagement />}
        {activeTab === 'locations' && !(isSuperAdmin() || hasAnyPermission(['location.read', 'location.manage', 'country.manage'])) && (
          <div className="p-6 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-800">
            You don't have permission to view Location Management. Required: location.read or country.manage.
          </div>
        )}
        {activeTab === 'countries' && (isSuperAdmin() || hasAnyPermission(['location.read', 'location.manage', 'country.manage'])) && <CountryManagement />}
        {activeTab === 'countries' && !(isSuperAdmin() || hasAnyPermission(['location.read', 'location.manage', 'country.manage'])) && (
          <div className="p-6 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-800">
            You don't have permission to view Country Management. Required: location.read or country.manage.
          </div>
        )}
        {activeTab === 'departments' && (isSuperAdmin() || hasAnyPermission(['department.read', 'department.manage', 'organization.manage'])) && <DepartmentManagement />}
        {activeTab === 'designations' && (isSuperAdmin() || hasAnyPermission(['designation.read', 'designation.manage', 'organization.manage'])) && <DesignationManagement />}
        {activeTab === 'permissions' && (isSuperAdmin() || hasAnyPermission(['permission.read', 'permission.manage', 'role.manage'])) && <PermissionManagement />}
        {activeTab === 'audit' && (isSuperAdmin() || hasAnyPermission(['audit.read', 'audit.logs', 'system.audit'])) && <AuditLogs />}
      </div>

      {/* Contact Dialog */}
      <ContactDialog
        user={selectedUser}
        isOpen={isContactDialogOpen}
        onClose={handleCloseContactDialog}
        onUpdate={handleUpdateContact}
        onChangePassword={handleChangePassword}
        mode={dialogMode}
        onCall={() => {}} // Not needed for admin view
        onSMS={() => {}} // Not needed for admin view
      />

      {/* Delete Confirmation Dialog */}
      <ConfirmationDialog
        isOpen={isDeleteConfirmOpen}
        title="Delete Contact"
        message={userToDelete ? 
          `Are you sure you want to delete "${userToDelete.name}"? This action cannot be undone.` :
          'Are you sure you want to delete this contact?'
        }
        confirmText="Delete"
        cancelText="Cancel"
        onConfirm={confirmDeleteContact}
        onClose={cancelDeleteContact}
        type="danger"
      />

      {/* Role Change Modal */}
      {isRoleChangeModalOpen && userToChangeRole && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md mx-4 shadow-xl">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-gray-900">Change Role</h3>
              <button
                onClick={cancelRoleChange}
                className="text-gray-400 hover:text-gray-600 transition-colors"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  User: {userToChangeRole.name}
                </label>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Service No: {userToChangeRole.service_no}
                </label>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Current Role: {userToChangeRole.role}
                </label>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  New Role *
                </label>
                <select
                  value={newRole}
                  onChange={(e) => setNewRole(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"
                  required
                  disabled={rolesLoading}
                >
                  <option value="">
                    {rolesLoading ? 'Loading roles...' : 'Select Role'}
                  </option>
                  {availableRoles.map(role => (
                    <option key={role.id} value={role.name}>
                      {role.name} - {role.description}
                    </option>
                  ))}
                </select>
                {rolesLoading && (
                  <p className="text-xs text-gray-500 mt-1">Loading roles from database...</p>
                )}
              </div>

              <div className="flex space-x-3 pt-4">
                <button
                  onClick={cancelRoleChange}
                  className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={confirmRoleChange}
                  disabled={!newRole || newRole === userToChangeRole.role}
                  className="flex-1 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Change Role
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Unit Dialog */}
      <UnitDialog
        unit={selectedUnit}
        isOpen={isUnitDialogOpen}
        onClose={() => setIsUnitDialogOpen(false)}
        onSuccess={handleUnitDialogSuccess}
        mode={unitDialogMode}
      />

      {/* Department Dialog */}
      <DepartmentDialog
        department={selectedDepartment}
        isOpen={isDepartmentDialogOpen}
        onClose={() => setIsDepartmentDialogOpen(false)}
        onSuccess={handleDepartmentDialogSuccess}
        mode={departmentDialogMode}
      />

      {/* Designation Dialog */}
      <DesignationDialog
        designation={selectedDesignation}
        isOpen={isDesignationDialogOpen}
        onClose={() => setIsDesignationDialogOpen(false)}
        onSuccess={handleDesignationDialogSuccess}
        mode={designationDialogMode}
      />
      
      <CountryDialog
        country={selectedCountry}
        isOpen={isCountryDialogOpen}
        onClose={() => setIsCountryDialogOpen(false)}
        onSuccess={handleCountryDialogSuccess}
        mode={countryDialogMode}
      />

      {/* Unit Delete Confirmation Dialog */}
      <ConfirmationDialog
        isOpen={isUnitDeleteOpen}
        title="Delete Unit"
        message={unitToDelete ? 
          `Are you sure you want to delete "${unitToDelete.name}"? This action cannot be undone.` :
          'Are you sure you want to delete this unit?'
        }
        confirmText="Delete"
        cancelText="Cancel"
        onConfirm={confirmDeleteUnit}
        onClose={cancelDeleteUnit}
        type="danger"
      />

      {/* Department Delete Confirmation Dialog */}
      <ConfirmationDialog
        isOpen={isDepartmentDeleteOpen}
        title="Delete Department"
        message={departmentToDelete ? 
          `Are you sure you want to delete "${departmentToDelete.name}"? This action cannot be undone.` :
          'Are you sure you want to delete this department?'
        }
        confirmText="Delete"
        cancelText="Cancel"
        onConfirm={confirmDeleteDepartment}
        onClose={cancelDeleteDepartment}
        type="danger"
      />

      {/* Designation Delete Confirmation Dialog */}
      <ConfirmationDialog
        isOpen={isDesignationDeleteOpen}
        title="Delete Designation"
        message={designationToDelete ? 
          `Are you sure you want to delete "${designationToDelete.name}"? This action cannot be undone.` :
          'Are you sure you want to delete this designation?'
        }
        confirmText="Delete"
        cancelText="Cancel"
        onConfirm={confirmDeleteDesignation}
        onClose={cancelDeleteDesignation}
        type="danger"
      />
      
      <ConfirmationDialog
        isOpen={isCountryDeleteOpen}
        title="Delete Country"
        message={countryToDelete ? 
          `Are you sure you want to delete "${countryToDelete.name}"? This action cannot be undone.` :
          'Are you sure you want to delete this country?'
        }
        confirmText="Delete"
        cancelText="Cancel"
        onConfirm={confirmDeleteCountry}
        onClose={cancelDeleteCountry}
        type="danger"
      />

      {/* Permission Dialog */}
      <PermissionModal
        permission={selectedPermission}
        isOpen={isPermissionDialogOpen}
        onClose={() => setIsPermissionDialogOpen(false)}
        onSuccess={handlePermissionDialogSuccess}
        mode={permissionDialogMode === 'view' ? 'edit' : permissionDialogMode}
        existingPermissions={permissions}
      />

      {/* Permission Delete Confirmation Dialog */}
      <ConfirmationDialog
        isOpen={isPermissionDeleteOpen}
        title="Delete Permission"
        message={permissionToDelete ? 
          `Are you sure you want to delete "${permissionToDelete.name}"? This action cannot be undone.` :
          'Are you sure you want to delete this permission?'
        }
        confirmText="Delete"
        cancelText="Cancel"
        onConfirm={confirmDeletePermission}
        onClose={cancelDeletePermission}
        type="danger"
      />

      {/* Notification */}
      {notification && (
        <div className={`fixed top-4 right-4 z-50 max-w-sm w-full bg-white rounded-lg shadow-lg border-l-4 ${
          notification.type === 'success' ? 'border-green-500' : 'border-red-500'
        }`}>
          <div className="p-4">
            <div className="flex items-start">
              <div className={`flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center ${
                notification.type === 'success' ? 'bg-green-100' : 'bg-red-100'
              }`}>
                {notification.type === 'success' ? (
                  <svg className="w-3 h-3 text-green-600" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                  </svg>
                ) : (
                  <svg className="w-3 h-3 text-red-600" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                  </svg>
                )}
              </div>
              <div className="ml-3 flex-1">
                <h3 className={`text-sm font-medium ${
                  notification.type === 'success' ? 'text-green-800' : 'text-red-800'
                }`}>
                  {notification.message}
                </h3>
                {notification.description && (
                  <p className={`mt-1 text-sm ${
                    notification.type === 'success' ? 'text-green-700' : 'text-red-700'
                  }`}>
                    {notification.description}
                  </p>
                )}
              </div>
              <button
                onClick={() => setNotification(null)}
                className={`ml-4 flex-shrink-0 ${
                  notification.type === 'success' ? 'text-green-400 hover:text-green-600' : 'text-red-400 hover:text-red-600'
                }`}
              >
                <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Admin;
