import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, Filter, Users, Building, Plus, X } from 'lucide-react';
import { useApp } from '../context/AppContext';
import { useAuth } from '../context/AuthContext';
import ContactCard from '../components/UI/ContactCard';
import ContactDialog from '../components/UI/ContactDialog';
import CreateOrganizationalDialog from '../components/UI/CreateOrganizationalDialog';
import DepartmentDropdown from '../components/UI/DepartmentDropdown';
import ExcelUploadDialog from '../components/UI/ExcelUploadDialog';
import OrganizationalStructureView from '../components/UI/OrganizationalStructureView';
import AddDepartmentDialog from '../components/UI/AddDepartmentDialog';
import EditDepartmentDialog from '../components/UI/EditDepartmentDialog';
import UnitDialog from '../components/UI/UnitDialog';
import ConfirmationDialog from '../components/UI/ConfirmationDialog';
import { useToast } from '../components/UI/ToastContainer';
import { User } from '../types';
import { organizationalApi, Unit as ApiUnit } from '../services/api';
import { Unit } from '../types';
import { apiCache } from '../utils/requestThrottler';

const Directory: React.FC = () => {
  const { 
    users, 
    createOrFindConversation, 
    setSelectedConversation,
    fetchContacts,
    createContact,
    updateContact,
    deleteContact,
    contactsLoading,
    contactsError,
    departments,
    departmentsLoading,
    departmentsError,
    units: contextUnits,
    unitsLoading: contextUnitsLoading,
    unitsError: contextUnitsError,
    deleteDepartment,
    fetchDepartments,
    fetchUnits: fetchContextUnits,
    contactsTotal
  } = useApp();
  const { hasPermission, hasAnyPermission, hasAllPermissions, isSuperAdmin } = useAuth();
  
  // Super Admin Override Function for PermissionComponent
  const PermissionComponentWithSuperAdmin = ({ permission, permissions, children, ...props }: any) => {
    const hasRequiredPermissions = React.useMemo(() => {
      if (isSuperAdmin()) return true; // Super Admin has access to everything
      
      if (permission) {
        return hasPermission(permission);
      }
      
      if (permissions) {
        if (props.requireAll) {
          return hasAllPermissions(permissions);
        } else {
          return hasAnyPermission(permissions);
        }
      }
      
      return true; // No permission required
    }, [permission, permissions, props.requireAll, hasPermission, hasAnyPermission, hasAllPermissions, isSuperAdmin]);

    // Don't render if user doesn't have required permissions
    if (!hasRequiredPermissions) {
      return null;
    }

    return (
      <div {...props}>
        {children}
      </div>
    );
  };
  const navigate = useNavigate();
  const { showSuccess, showError, ToastContainer } = useToast();
  const [searchQuery, setSearchQuery] = useState('');

  // 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('');
    }
  };
  const [selectedUnit, setSelectedUnit] = useState('all');
  const [selectedUnitId, setSelectedUnitId] = useState<number | string>('all');
  const [selectedDepartment, setSelectedDepartment] = useState<number | string>('all');
  const [showSearchSuggestions, setShowSearchSuggestions] = useState(false);
  const [viewMode, setViewMode] = useState<'grid' | 'structure'>('structure'); // Default to tree view
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  
  // Organizational creation dialogs
  const [isCreateUnitDialogOpen, setIsCreateUnitDialogOpen] = useState(false);
  const [isEditUnitDialogOpen, setIsEditUnitDialogOpen] = useState(false);
  const [editingUnit, setEditingUnit] = useState<Unit | null>(null);
  const [isExcelUploadDialogOpen, setIsExcelUploadDialogOpen] = useState(false);
  const [isAddDepartmentDialogOpen, setIsAddDepartmentDialogOpen] = useState(false);
  const [isEditDepartmentDialogOpen, setIsEditDepartmentDialogOpen] = useState(false);
  const [editingDepartment, setEditingDepartment] = useState<{
    id: number;
    name: string;
    description?: string;
    parent_id?: number;
  } | null>(null);
  const [addDepartmentContext, setAddDepartmentContext] = useState<{
    unitName: string;
    unitId: number;
    parentDepartmentId?: number;
    parentDepartmentName?: string;
  } | null>(null);
  
  // Context for create contact dialog
  const [createContactContext, setCreateContactContext] = useState<{
    unitName: string;
    departmentName: string;
  } | null>(null);
  
  // Parent contact for hierarchical creation
  const [parentContact, setParentContact] = useState<User | null>(null);
  
  // Confirmation dialog state
  const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
  const [contactToDelete, setContactToDelete] = useState<User | null>(null);
  
  // Department delete confirmation state
  const [isDepartmentDeleteConfirmOpen, setIsDepartmentDeleteConfirmOpen] = useState(false);
  const [departmentToDelete, setDepartmentToDelete] = useState<{
    id: number;
    name: string;
  } | null>(null);

  // Unit delete confirmation state
  const [isUnitDeleteConfirmOpen, setIsUnitDeleteConfirmOpen] = useState(false);
  const [unitToDelete, setUnitToDelete] = useState<{
    id: number;
    name: string;
  } | null>(null);

  // Units state - removed, using contextUnits directly

  // Frontend-only search - no need for designations API data

  // Legacy units from contacts (fallback)
  const legacyUnits = Array.from(new Set(users.map(u => u.unit)));

  // Fetch units when view mode changes
  useEffect(() => {
    fetchContextUnits(viewMode === 'structure');
  }, [viewMode, fetchContextUnits]);

  // Real-time data refresh utility
  const refreshAllData = useCallback(async (operation: string = 'operation') => {
    console.log(`Refreshing all data after ${operation}...`);
    try {
      // Clear cache to ensure fresh data
      apiCache.clear();
      
      await Promise.all([
        fetchContacts({ 
          tree: viewMode === 'structure',
          limit: 1000,
          include_inactive: true
        }),
        fetchDepartments(),
        fetchContextUnits(viewMode === 'structure')
      ]);
      console.log(`All data refreshed successfully after ${operation}`);
    } catch (error) {
      console.error(`❌ Failed to refresh data after ${operation}:`, error);
    }
  }, [fetchContacts, fetchDepartments, fetchContextUnits, viewMode]);

  // Fetch fresh data on component mount
  useEffect(() => {
    refreshAllData('component mount');
  }, [refreshAllData]);

  // Fetch contacts on component mount
  useEffect(() => {
    console.log('Directory component mounted, fetching contacts...');
    fetchContacts({ 
      tree: viewMode === 'structure',
      limit: 1000, // Get all contacts
      include_inactive: false // Show only active contacts
    });
  }, [fetchContacts, viewMode]);

  // Handle edit event from Contact Details view
  useEffect(() => {
    const handleContactEdit = (event: CustomEvent) => {
      const user = event.detail;
      setEditingUser(user);
      setIsEditDialogOpen(true);
      setIsDialogOpen(false); // Close the view dialog
    };

    window.addEventListener('contactEdit', handleContactEdit as EventListener);
    
    return () => {
      window.removeEventListener('contactEdit', handleContactEdit as EventListener);
    };
  }, []);

  // Handle unit change
  const handleUnitChange = (unitName: string) => {
    setSelectedUnit(unitName);
    if (unitName === 'all') {
      setSelectedUnitId('all');
    } else {
      const unit = contextUnits.find(u => u.name === unitName);
      // If unit not found in API units, use the unit name as the ID for legacy units
      setSelectedUnitId(unit ? unit.id : unitName);
    }
  };

  // Frontend-only search - no backend API calls
  // Search is handled purely in the filteredUsers filter below

  // Generate search suggestions from available data
  const getSearchSuggestions = () => {
    if (!searchQuery || searchQuery.length < 2) return [];
    
    const suggestions = new Set<string>();
    const searchLower = searchQuery.toLowerCase();
    
    users.forEach(user => {
      // Add unique suggestions from various fields
      if (user.name && user.name.toLowerCase().includes(searchLower)) {
        suggestions.add(user.name);
      }
      if (user.designation && user.designation.toLowerCase().includes(searchLower)) {
        suggestions.add(user.designation);
      }
      if (user.department && user.department.toLowerCase().includes(searchLower)) {
        suggestions.add(user.department);
      }
      if (user.unit && user.unit.toLowerCase().includes(searchLower)) {
        suggestions.add(user.unit);
      }
      if (user.rank && user.rank.toLowerCase().includes(searchLower)) {
        suggestions.add(user.rank);
      }
      if (user.email && user.email.toLowerCase().includes(searchLower)) {
        suggestions.add(user.email);
      }
      if (user.phone && user.phone.toLowerCase().includes(searchLower)) {
        suggestions.add(user.phone);
      }
      if (user.mobile && user.mobile.toLowerCase().includes(searchLower)) {
        suggestions.add(user.mobile);
      }
    });
    
    return Array.from(suggestions).slice(0, 5); // Limit to 5 suggestions
  };

  const searchSuggestions = getSearchSuggestions();

  // Debug logging for Permissions (removed for production)

  const filteredUsers = users.filter(user => {
    try {
      // Enhanced comprehensive search across all available fields
      const searchLower = (searchQuery || '').toLowerCase();
      const matchesSearch = !searchQuery || searchQuery.length < 2 ? true : 
        // Personal Information
        (user.name && typeof user.name === 'string' && user.name.toLowerCase().includes(searchLower)) ||
        (user.service_no && typeof user.service_no === 'string' && user.service_no.toLowerCase().includes(searchLower)) ||
        (user.rank && typeof user.rank === 'string' && user.rank.toLowerCase().includes(searchLower)) ||
        
        // Contact Information
        (user.email && typeof user.email === 'string' && user.email.toLowerCase().includes(searchLower)) ||
        (user.phone && typeof user.phone === 'string' && user.phone.toLowerCase().includes(searchLower)) ||
        (user.mobile && typeof user.mobile === 'string' && user.mobile.toLowerCase().includes(searchLower)) ||
        (user.alternative_mobile && typeof user.alternative_mobile === 'string' && user.alternative_mobile.toLowerCase().includes(searchLower)) ||
        
        // Organizational Information
        (user.unit && typeof user.unit === 'string' && user.unit.toLowerCase().includes(searchLower)) ||
        (user.department && typeof user.department === 'string' && user.department.toLowerCase().includes(searchLower)) ||
        (user.designation && typeof user.designation === 'string' && user.designation.toLowerCase().includes(searchLower)) ||
        (user.branch && typeof user.branch === 'string' && user.branch.toLowerCase().includes(searchLower)) ||
        (user.subBranch && typeof user.subBranch === 'string' && user.subBranch.toLowerCase().includes(searchLower)) ||
        
        // Role and Status
        (user.role && typeof user.role === 'string' && user.role.toLowerCase().includes(searchLower)) ||
        (user.status && typeof user.status === 'string' && user.status.toLowerCase().includes(searchLower));
    
    const matchesUnit = selectedUnit === 'all' || user.unit === selectedUnit;
    
    // Match department by name (since User type has department as string)
    const matchesDepartment = selectedDepartment === 'all' || 
      (selectedDepartment !== 'all' && departments.find(dept => dept.id === selectedDepartment)?.name === user.department);
    
    return matchesSearch && matchesUnit && matchesDepartment;
    } catch (error) {
      console.error('Error filtering user:', error);
      return true; // Show user if filtering fails
    }
  }).sort((a, b) => (a.order_id || 0) - (b.order_id || 0)); // Sort by order_id in ascending order

  // Filter units based on selected unit
  const filteredUnits = selectedUnit === 'all' 
    ? contextUnits 
    : contextUnits.filter(unit => unit.name === selectedUnit);

  // Filter departments based on selected unit
  const filteredDepartments = departments;

  // Debug: Show frontend search results summary
  if (searchQuery.length >= 2) {
    console.log(`Frontend Contact Search Results:`);
    console.log(`Search Query: "${searchQuery}" (comprehensive search across all fields)`);
    console.log(`Total Contacts: ${users.length}`);
    console.log(`Filtered Contacts: ${filteredUsers.length}`);
  }

  // Debug: Show all contacts and their units (only when needed)
  if (process.env.NODE_ENV === 'development') {
    console.log(`All Contacts Debug:`);
    console.log(`Total Contacts: ${users.length}`);
    console.log(`Contacts by Unit:`, users.reduce((acc, user) => {
      acc[user.unit] = (acc[user.unit] || 0) + 1;
      return acc;
    }, {} as Record<string, number>));
  }


  const handleContactClick = (user: User) => {
    setSelectedUser(user);
    setIsDialogOpen(true);
  };

  const handleMessage = (user: User) => {
    // Create or find conversation with the user
    const conversation = createOrFindConversation(user.id);
    
    // Set the conversation as selected
    setSelectedConversation(conversation);
    
    // Close dialog and navigate to conversations page
    setIsDialogOpen(false);
    navigate('/conversations');
  };

  const handleCall = (user: User) => {
    // For now, just show a beautiful message. In a real app, this would initiate a call
    showSuccess(
      'Call Initiated',
      `Calling ${user.role} at ${user.phone}`,
      3000
    );
    setIsDialogOpen(false);
  };

  const handleSMS = (user: User) => {
    // For now, just show a beautiful message. In a real app, this would open SMS
    showSuccess(
      'SMS Ready',
      `SMS interface opened for ${user.role} at ${user.phone}`,
      3000
    );
    setIsDialogOpen(false);
  };

  const handleCloseDialog = () => {
    setIsDialogOpen(false);
    setSelectedUser(null);
  };

  const handleCreateContact = async (contactData: any) => {
    try {
      console.log('🚀 Starting contact creation...', contactData);
      const createdContact = await createContact(contactData);
      console.log('✅ Contact created successfully:', createdContact);
      
      // Close dialog first
      setIsCreateDialogOpen(false);
      setCreateContactContext(null);
      setParentContact(null);
      
      // Immediately refresh all data
      await refreshAllData('contact creation');
      
      // Show beautiful success message
      const contactName = contactData.name || (createdContact as any)?.name || 'New Contact';
      showSuccess(
        'Contact Created Successfully! ✨',
        `${contactName} has been added to the directory with default password set to their mobile number.`,
        6000
      );
      
    } catch (error) {
      console.error('Failed to create contact:', error);
      showError(
        'Failed to Create Contact',
        'There was an error creating the contact. Please try again.',
        5000
      );
    }
  };

  const handleUpdateContact = async (contactData: any) => {
    if (!editingUser) return;
    
    try {
      console.log('🚀 Starting contact update...', contactData);
      await updateContact(editingUser.id, contactData);
      console.log('✅ Contact updated successfully');
      
      // Close dialog first
      setIsEditDialogOpen(false);
      setEditingUser(null);
      
      // Immediately refresh all data
      await refreshAllData('contact update');
      
      // Show beautiful success message
      const contactName = contactData.name || editingUser.name || 'Contact';
      showSuccess(
        'Contact Updated Successfully! ✨',
        `${contactName} has been updated successfully.`,
        5000
      );
      
    } catch (error) {
      console.error('Failed to update contact:', error);
      showError(
        'Failed to Update Contact',
        'There was an error updating the contact. Please try again.',
        5000
      );
    }
  };

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

  const confirmDeleteContact = async () => {
    if (!contactToDelete) return;
    
    try {
      console.log('🚀 Starting contact deletion...', contactToDelete);
      const opts: { source: 'directory'; scope?: 'department' | 'all'; department_id?: number } = { source: 'directory' };
      if (selectedDepartment !== 'all' && typeof selectedDepartment === 'number') {
        opts.scope = 'department';
        opts.department_id = selectedDepartment as number;
      }
      await deleteContact(contactToDelete.id, opts);
      console.log('✅ Contact deleted successfully');
      
      // Close dialog first
      setIsDeleteConfirmOpen(false);
      setContactToDelete(null);
      
      // Immediately refresh all data
      await refreshAllData('contact deletion');
      
      const contactName = contactToDelete.name || contactToDelete.designation || contactToDelete.service_no || 'this contact';
      showSuccess(
        'Contact Deleted Successfully! ✨',
        `${contactName} has been removed from the directory.`,
        5000
      );
      
    } catch (error) {
      console.error('Failed to delete contact:', error);
      showError(
        'Failed to Delete Contact',
        'There was an error deleting the contact. Please try again.',
        5000
      );
    }
  };

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

  const handleExcelUploadSuccess = async () => {
    // Immediately refresh all data
    await refreshAllData('Excel upload');
    
    // Show beautiful success message
    showSuccess(
      'Excel Upload Successful! ✨',
      'Contacts have been successfully imported from the Excel file.',
      6000
    );
  };

  const handleAddDepartment = (unitName: string, unitId: number) => {
    setAddDepartmentContext({ unitName, unitId });
    setIsAddDepartmentDialogOpen(true);
  };

  const handleAddSubDepartment = (departmentId: number, departmentName: string) => {
    setAddDepartmentContext({ 
      unitName: '',
      unitId: 0,
      parentDepartmentId: departmentId,
      parentDepartmentName: departmentName
    });
    setIsAddDepartmentDialogOpen(true);
  };

  const handleEditDepartment = (departmentId: number) => {
    const department = departments.find(dept => dept.id === departmentId);
    if (department) {
      setEditingDepartment({
        id: department.id,
        name: department.name,
        description: department.description,
        parent_id: department.parent_id || undefined
      });
      setIsEditDepartmentDialogOpen(true);
    }
  };

  const handleDepartmentCreated = async () => {
    try {
      // Immediately refresh all data
      await refreshAllData('department creation');
      
      // Show beautiful success message
      showSuccess(
        'Department Created Successfully! ✨',
        'New department has been added to the organizational structure.',
        5000
      );
    } catch (error) {
      console.error('Failed to refresh after department creation:', error);
      showError(
        'Refresh Error',
        'Department created but failed to refresh the list. Please reload the page.',
        5000
      );
    }
  };

  const handleDepartmentUpdated = async () => {
    try {
      // Immediately refresh all data
      await refreshAllData('department update');
      
      showSuccess(
        'Department Updated Successfully! ✨',
        'Department information has been updated.',
        5000
      );
    } catch (error) {
      console.error('Failed to refresh after department update:', error);
      showError(
        'Refresh Error',
        'Department updated but failed to refresh the list. Please reload the page.',
        5000
      );
    }
  };

  // Unit handlers
  const handleUnitCreated = async () => {
    try {
      // Immediately refresh all data
      await refreshAllData('unit creation');
      
      showSuccess(
        'Unit Created Successfully! ✨',
        'New unit has been added to the organizational structure.',
        5000
      );
    } catch (error) {
      console.error('Failed to refresh after unit creation:', error);
      showError(
        'Refresh Error',
        'Unit created but failed to refresh the list. Please reload the page.',
        5000
      );
    }
  };

  // Convert ApiUnit to Unit type for UnitDialog
  const convertApiUnitToUnit = (apiUnit: ApiUnit): Unit => {
    return {
      id: apiUnit.id,
      name: apiUnit.name,
      order_id: apiUnit.order_id,
      code: apiUnit.code || '',
      description: apiUnit.description || '',
      parent_id: apiUnit.parent_id,
      parent_name: apiUnit.parent_name,
      is_active: apiUnit.is_active === 1, // Convert number to boolean
      total_users: apiUnit.total_users || 0,
      created_at: apiUnit.created_at || '',
      updated_at: apiUnit.updated_at || ''
    };
  };

  const handleEditUnit = (unitId: number, unitName: string) => {
    console.log('Edit Unit:', unitId, unitName);
    // Find the unit from the contextUnits array
    const apiUnit = contextUnits.find(u => u.id === unitId || u.name === unitName);
    if (apiUnit) {
      const unit = convertApiUnitToUnit(apiUnit);
      setEditingUnit(unit);
      setIsEditUnitDialogOpen(true);
    } else {
      console.error('Unit not found:', unitId, unitName);
      showError(
        'Unit Not Found',
        'The selected unit could not be found. Please try again.',
        3000
      );
    }
  };

  const handleUnitUpdated = async () => {
    try {
      // Immediately refresh all data
      await refreshAllData('unit update');
      
      showSuccess(
        'Unit Updated Successfully! ',
        'Unit information has been updated.',
        5000
      );
      
      // Close the dialog
      setIsEditUnitDialogOpen(false);
      setEditingUnit(null);
    } catch (error) {
      console.error('Failed to refresh after unit update:', error);
      showError(
        'Refresh Error',
        'Unit updated but failed to refresh the list. Please reload the page.',
        5000
      );
    }
  };

  const handleDeleteDepartment = (departmentId: number, departmentName: string) => {
    setDepartmentToDelete({ id: departmentId, name: departmentName });
    setIsDepartmentDeleteConfirmOpen(true);
  };

  const confirmDeleteDepartment = async () => {
    if (!departmentToDelete) return;
    
    try {
      await deleteDepartment(departmentToDelete.id);
      
      // Close dialog first
      setIsDepartmentDeleteConfirmOpen(false);
      setDepartmentToDelete(null);
      
      // Immediately refresh all data
      await refreshAllData('department deletion');
      
      showSuccess(
        'Department Deleted Successfully! ✨',
        `"${departmentToDelete.name}" has been removed from the organizational structure.`,
        5000
      );
    } catch (error) {
      console.error('Failed to delete department:', error);
      showError(
        'Failed to Delete Department',
        `There was an error deleting the department: ${error instanceof Error ? error.message : 'Unknown error'}`,
        5000
      );
    } finally {
      setIsDepartmentDeleteConfirmOpen(false);
      setDepartmentToDelete(null);
    }
  };

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

  const handleDeleteUnit = (unitId: number, unitName: string) => {
    setUnitToDelete({ id: unitId, name: unitName });
    setIsUnitDeleteConfirmOpen(true);
  };

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

      if (response.ok) {
        // Close dialog first
        setIsUnitDeleteConfirmOpen(false);
        setUnitToDelete(null);
        
        // Immediately refresh all data
        await refreshAllData('unit deletion');
        
        showSuccess(
          'Unit Deleted Successfully! ✨',
          `"${unitToDelete.name}" has been removed from the organizational structure.`,
          5000
        );
      } else {
        throw new Error('Failed to delete unit');
      }
    } catch (error) {
      console.error('Failed to delete unit:', error);
      showError(
        'Failed to Delete Unit',
        `There was an error deleting the unit: ${error instanceof Error ? error.message : 'Unknown error'}`,
        5000
      );
    } finally {
      setIsUnitDeleteConfirmOpen(false);
      setUnitToDelete(null);
    }
  };

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

  const handleCloseCreateDialog = () => {
    setIsCreateDialogOpen(false);
    setCreateContactContext(null);
    setParentContact(null);
  };

  const handleCloseEditDialog = () => {
    setIsEditDialogOpen(false);
    setEditingUser(null);
  };

  // Organizational creation handlers
  const handleCreateUnit = async (unitData: any) => {
    try {
      // Prepare the request body according to the API specification
      const createUnitRequest = {
        name: unitData.name,
        code: unitData.code || '',
        description: unitData.description || undefined,
        parent_id: unitData.parent_id || null
      };

      const response = await organizationalApi.createUnit(createUnitRequest);
      
      if (response.status === 'success') {
        setIsCreateUnitDialogOpen(false);
        
        // Immediately refresh all data
        await refreshAllData('unit creation');
        
        showSuccess(
          'Unit Created Successfully! ✨',
          `"${unitData.name}" has been added to the organizational structure.`,
          5000
        );
      } else {
        showError(
          'Failed to Create Unit',
          `There was an error creating the unit: ${response.message || 'Unknown error'}`,
          5000
        );
      }
    } catch (error) {
      console.error('Failed to create unit:', error);
      showError(
        'Failed to Create Unit',
        `There was an error creating the unit: ${error instanceof Error ? error.message : 'Unknown error'}`,
        5000
      );
    }
  };

  

  // Access Control - Super Admin has full access
  if (!isSuperAdmin() && !hasAnyPermission(['directory.access', 'contact.read'])) {
    return (
      <div className="p-6 space-y-6">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Access Denied</h1>
            <p className="text-sm text-gray-600 mt-1">You don't have permission to access the directory</p>
          </div>
        </div>
        <div className="flex items-center justify-center h-64">
          <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
            <div className="text-red-600 mb-2">
              <Users className="h-12 w-12 mx-auto" />
            </div>
            <h3 className="text-lg font-semibold text-red-800 mb-2">Directory Access Required</h3>
            <p className="text-sm text-red-700">
              You need directory permissions to view this page. Please contact your administrator.
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <h1 className="text-3xl font-bold text-gray-900">Contact Directory</h1>
        
        <div className="flex items-center space-x-4">
          {/* Add Unit button - Dynamic Permission Check */}
          {(isSuperAdmin() || hasAnyPermission(['unit.create'])) && (
            <button
              onClick={() => setIsCreateUnitDialogOpen(true)}
              className="flex items-center space-x-2 bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors"
            >
              <Plus className="h-5 w-5" />
              <span>Add Unit</span>
            </button>
          )}
          
          {/* Excel Upload button - Dynamic Permission Check */}
          {(isSuperAdmin() || hasAnyPermission(['contact.import'])) && (
            <button
              onClick={() => setIsExcelUploadDialogOpen(true)}
              className="flex items-center space-x-2 bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors"
            >
              <Plus className="h-5 w-5" />
              <span>Upload Excel</span>
            </button>
          )}
          
          <div className="flex items-center space-x-2">
            {/* Search Button - Always visible */}
           
            
            {/* Grid View Button - Dynamic Permission Check */}
            {(isSuperAdmin() || hasAnyPermission(['directory.grid_view'])) && (
              <button
                onClick={() => setViewMode('grid')}
                className={`p-2 rounded-lg transition-colors ${
                  viewMode === 'grid' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'
                }`}
                title="Grid View"
              >
                <Users className="h-5 w-5" />
              </button>
            )}
            
            {/* Tree View Button - Dynamic Permission Check */}
            {(isSuperAdmin() || hasAnyPermission(['directory.tree_view'])) && (
              <button
                onClick={() => setViewMode('structure')}
                className={`p-2 rounded-lg transition-colors ${
                  viewMode === 'structure' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'
                }`}
                title="Complete Organizational Structure"
              >
                <Building className="h-5 w-5" />
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Filters - Always show search, hide other filters in structure view */}
      {(isSuperAdmin() || hasAnyPermission(['directory.filter', 'directory.search'])) && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div className="mb-4 flex items-center space-x-2">
              <Filter className="h-5 w-5 text-gray-400" />
              <h3 className="text-lg font-semibold text-gray-900">Filters</h3>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          {/* Search Filter - Always visible */}
          {(isSuperAdmin() || hasAnyPermission(['directory.search'])) && (
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                <input
                  type="text"
                  placeholder="Search by name, phone, mobile, email, designation, department, unit, rank, service no..."
                  value={searchQuery}
                onChange={(e) => updateSearchQuery(e.target.value)}
                onFocus={() => setShowSearchSuggestions(true)}
                onBlur={() => setTimeout(() => setShowSearchSuggestions(false), 200)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    e.preventDefault();
                  }
                }}
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              {searchQuery && (
                <button
                  type="button"
                  onClick={() => updateSearchQuery('')}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                >
                  <X className="h-4 w-4" />
                </button>
              )}
              
              {/* Search Suggestions Dropdown */}
              {showSearchSuggestions && searchSuggestions.length > 0 && (
                <div className="absolute top-full left-0 right-0 mt-1 bg-white border border-gray-300 rounded-lg shadow-lg z-50 max-h-60 overflow-y-auto">
                  {searchSuggestions.map((suggestion, index) => (
                    <button
                      key={index}
                      type="button"
                      onClick={() => {
                        updateSearchQuery(suggestion);
                        setShowSearchSuggestions(false);
                      }}
                      className="w-full px-4 py-2 text-left hover:bg-gray-100 transition-colors text-sm"
                    >
                      {suggestion}
                    </button>
                  ))}
              </div>
              )}
            </div>
          )}
            
          {/* Unit Filter - Always visible */}
          {(isSuperAdmin() || hasAnyPermission(['directory.unit_filter'])) && (
            <div className="flex items-center space-x-2">
              <select
                value={selectedUnit}
                onChange={(e) => handleUnitChange(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                disabled={contextUnitsLoading}
              >
                <option value="all">All Units</option>
                {contextUnitsLoading ? (
                  <option value="" disabled>Loading units...</option>
                ) : contextUnitsError ? (
                  <option value="" disabled>Error loading units</option>
                ) : (
                  // Combine units from API and legacy units from users, sorted by order_id
                  Array.from(new Set([
                    ...(contextUnits.length > 0 ? contextUnits.map(unit => unit.name) : []),
                    ...legacyUnits
                  ])).sort((a, b) => {
                    // Find the unit objects to get their order_id
                    const unitA = contextUnits.find(unit => unit.name === a);
                    const unitB = contextUnits.find(unit => unit.name === b);
                    
                    // If both units exist in contextUnits, sort by order_id
                    if (unitA && unitB) {
                      return unitA.order_id - unitB.order_id;
                    }
                    
                    // If only one exists, prioritize it
                    if (unitA) return -1;
                    if (unitB) return 1;
                    
                    // If neither exists (legacy units), use alphabetical order
                    return a.localeCompare(b);
                  }).map(unitName => (
                    <option key={unitName} value={unitName}>{unitName}</option>
                  ))
                )}
              </select>
              {contextUnitsError && (
                <button
                  onClick={() => {
                    console.log('Retrying units fetch...');
                    refreshAllData('units retry');
                  }}
                  disabled={contextUnitsLoading}
                  className="p-2 text-red-500 hover:text-red-700 hover:bg-red-50 rounded transition-colors"
                  title="Retry loading units"
                >
                  <svg className={`h-4 w-4 ${contextUnitsLoading ? 'animate-spin' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                </button>
              )}
            </div>
          )}

          {/* Department Filter - Always visible */}
          {(isSuperAdmin() || hasAnyPermission(['directory.department_filter'])) && (
            <div className="flex items-center space-x-2">
              <DepartmentDropdown
                value={selectedDepartment}
                onChange={setSelectedDepartment}
                placeholder="All Departments"
                unitId={selectedUnitId}
                className="flex-1"
              />
            </div>
          )}

          {/* Clear All Filters Button */}
          {(searchQuery || selectedUnit !== 'all' || selectedDepartment !== 'all') && (
            <button
              type="button"
              onClick={() => {
                updateSearchQuery('');
                setSelectedUnit('all');
                setSelectedDepartment('all');
              }}
              className="flex items-center justify-center space-x-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
            >
              <X className="h-4 w-4" />
              <span>Clear All</span>
            </button>
          )}
          </div>
        </div>
      )}

      {/* Results */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <div className="mb-4 flex justify-between items-center">
          <div className="flex items-center space-x-2">
            <Filter className="h-5 w-5 text-gray-400" />
          <p className="text-gray-600">
            {contactsLoading ? 'Loading contacts...' : 
             contactsError ? `Error: ${contactsError}` :
             `Showing ${filteredUsers.length} of ${contactsTotal} contacts`}
          </p>
        </div>
          {/* Global retry button for all data */}
          {(contactsError || contextUnitsError || departmentsError) && (
            <button
              onClick={() => refreshAllData('manual retry')}
              disabled={contactsLoading || contextUnitsLoading || departmentsLoading}
              className="flex items-center space-x-2 px-3 py-1 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              title="Retry loading all data"
            >
              {(contactsLoading || contextUnitsLoading || departmentsLoading) ? (
                <>
                  <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white"></div>
                  <span>Retrying...</span>
                </>
              ) : (
                <>
                  <svg className="h-3 w-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                  <span>Retry All</span>
                </>
              )}
            </button>
          )}
        </div>

        {contactsLoading && (
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p className="text-gray-500">Loading contacts...</p>
          </div>
        )}

        {contactsError && (
          <div className="text-center py-12">
            <div className="text-red-500 mb-4">
              <svg className="h-12 w-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <p className="text-red-500 mb-4">{contactsError}</p>
            <div className="space-x-4">
              <button
                onClick={() => {
                  console.log('Retrying contacts fetch...');
                  refreshAllData('contacts retry');
                }}
                disabled={contactsLoading}
                className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2 mx-auto"
              >
                {contactsLoading ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                    <span>Retrying...</span>
                  </>
                ) : (
                  <>
                    <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                    </svg>
                    <span>Retry</span>
                  </>
                )}
              </button>
              {contactsError.includes('Access token') && (
                <button
                  onClick={() => navigate('/login')}
                  className="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors"
                >
                  Login Again
                </button>
              )}
            </div>
          </div>
        )}

        {!contactsLoading && !contactsError && (
          <>
            {viewMode === 'grid' ? (
              (isSuperAdmin() || hasAnyPermission(['directory.grid_view'])) && (
                <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                  {filteredUsers.map(user => (
                      <ContactCard 
                      key={user.id}
                        user={user}
                        viewMode={viewMode}
                        onClick={() => handleContactClick(user)}
                        onEdit={(user) => {
                          setEditingUser(user);
                          setIsEditDialogOpen(true);
                        }}
                      onCreateChild={(user) => {
                        console.log('Create child user for parent:', user);
                        // Set parent contact and open create contact dialog
                      setParentContact(user);
                      setIsCreateDialogOpen(true);
                    }}
                    onDelete={handleDeleteContact}
                    showActions={hasAnyPermission(['user.delete', 'contact.delete'])}
                    isAdmin={hasAnyPermission(['user.manage_roles', 'admin.access'])}
                    isSuperAdmin={hasAnyPermission(['super_admin.access'])}
                  />
                ))}
              </div>
              )
            ) : (
              (isSuperAdmin() || hasAnyPermission(['directory.tree_view'])) && (
                <>
                  {/* Show search results in a special format when searching */}
                  {searchQuery && searchQuery.length >= 2 ? (
                    <div className="space-y-4">
                      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <h3 className="text-lg font-semibold text-blue-900 mb-2">
                          Search Results for "{searchQuery}"
                        </h3>
                        <p className="text-sm text-blue-700 mb-4">
                          Found {filteredUsers.length} contact(s) matching your search
                        </p>
                        
                        {/* Show search results in a flat list */}
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                          {filteredUsers.map(user => (
                            <ContactCard 
                              key={user.id}
                              user={user}
                              viewMode="grid"
                              onClick={() => handleContactClick(user)}
                              onEdit={(user) => {
                                setEditingUser(user);
                                setIsEditDialogOpen(true);
                              }}
                              onDelete={handleDeleteContact}
                              showActions={hasAnyPermission(['user.delete', 'contact.delete'])}
                              isAdmin={hasAnyPermission(['user.manage_roles', 'admin.access'])}
                              isSuperAdmin={hasAnyPermission(['super_admin.access'])}
                            />
                          ))}
                        </div>
                      </div>
                      
                      {/* Also show the organizational structure with filtered users */}
                      <div className="border-t pt-4">
                        <h3 className="text-lg font-semibold text-gray-900 mb-4">
                          Organizational Structure (Filtered)
                        </h3>
                <OrganizationalStructureView
                  users={filteredUsers}
                  departments={filteredDepartments}
                  units={filteredUnits}
                  totalContacts={contactsTotal}
                  onUserClick={handleContactClick}
                  onEditUser={(user) => {
                    setEditingUser(user);
                    setIsEditDialogOpen(true);
                  }}
                  onAddUser={(unitName, departmentName) => {
                    setCreateContactContext({ unitName, departmentName });
                    setIsCreateDialogOpen(true);
                  }}
                  onAddDepartment={handleAddDepartment}
                          onEditDepartment={handleEditDepartment}
                          onEditUnit={handleEditUnit}
                          onDeleteDepartment={handleDeleteDepartment}
                          onDeleteUnit={handleDeleteUnit}
                  showActions={hasAnyPermission(['user.create', 'department.create'])}
                  isAdmin={hasAnyPermission(['user.manage_roles', 'admin.access'])}
                  isSuperAdmin={hasAnyPermission(['super_admin.access'])}
                  onAddSubDepartment={handleAddSubDepartment}
                  onCreateChild={(user) => {
                    console.log('Create child user for parent:', user);
                    setParentContact(user);
                    setIsCreateDialogOpen(true);
                  }}
                  onDeleteUser={handleDeleteContact}
                        />
                      </div>
                    </div>
                  ) : (
                    /* Show normal organizational structure when not searching */
                    <OrganizationalStructureView
                      users={filteredUsers}
                      departments={filteredDepartments}
                      units={filteredUnits}
                      totalContacts={contactsTotal}
                      onUserClick={handleContactClick}
                      onEditUser={(user) => {
                        setEditingUser(user);
                        setIsEditDialogOpen(true);
                      }}
                      onAddUser={(unitName, departmentName) => {
                        setCreateContactContext({ unitName, departmentName });
                        setIsCreateDialogOpen(true);
                      }}
                      onAddDepartment={handleAddDepartment}
                      onEditDepartment={handleEditDepartment}
                      onEditUnit={handleEditUnit}
                  onDeleteDepartment={handleDeleteDepartment}
                      onDeleteUnit={handleDeleteUnit}
                      showActions={hasAnyPermission(['user.create', 'department.create'])}
                      isAdmin={hasAnyPermission(['user.manage_roles', 'admin.access'])}
                      isSuperAdmin={hasAnyPermission(['super_admin.access'])}
                      onAddSubDepartment={handleAddSubDepartment}
                      onCreateChild={(user) => {
                        console.log('Create child user for parent:', user);
                        setParentContact(user);
                        setIsCreateDialogOpen(true);
                      }}
                      onDeleteUser={handleDeleteContact}
                    />
                  )}
                </>
              )
            )}
          </>
        )}

        {!contactsLoading && !contactsError && filteredUsers.length === 0 && (
          <div className="text-center py-12">
            <Users className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <p className="text-gray-500">No contacts found matching your search criteria. Try searching by designation using frontend search.</p>
            {/* Excel Upload button - Super Admin Override */}
            <PermissionComponentWithSuperAdmin permission="user.excel_upload">
              <button
                onClick={() => setIsExcelUploadDialogOpen(true)}
                className="mt-4 bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors"
              >
                Upload Excel
              </button>
            </PermissionComponentWithSuperAdmin>
          </div>
        )}
      </div>

      {/* Contact Dialog */}
      <ContactDialog
        user={selectedUser}
        isOpen={isDialogOpen}
        onClose={handleCloseDialog}
        onMessage={handleMessage}
        onCall={handleCall}
        onSMS={handleSMS}
        onUpdate={handleUpdateContact}
      />

      {/* Create Contact Dialog */}
      <ContactDialog
        user={null}
        isOpen={isCreateDialogOpen}
        onClose={handleCloseCreateDialog}
        onMessage={handleMessage}
        onCall={handleCall}
        onSMS={handleSMS}
        onCreate={handleCreateContact}
        mode="create"
        defaultUnitName={createContactContext?.unitName}
        defaultDepartmentName={createContactContext?.departmentName}
        parentUser={parentContact}
        availableUsers={users}
      />

      {/* Edit Contact Dialog */}
      <ContactDialog
        user={editingUser}
        isOpen={isEditDialogOpen}
        onClose={handleCloseEditDialog}
        onMessage={handleMessage}
        onCall={handleCall}
        onSMS={handleSMS}
        onUpdate={handleUpdateContact}
        mode="edit"
      />

      {/* Organizational Creation Dialogs */}
      {isCreateUnitDialogOpen && (
        <CreateOrganizationalDialog
          isOpen={isCreateUnitDialogOpen}
          onClose={() => setIsCreateUnitDialogOpen(false)}
          onSubmit={handleCreateUnit}
          type="unit"
        />
      )}


      {/* Excel Upload Dialog */}
      <ExcelUploadDialog
        isOpen={isExcelUploadDialogOpen}
        onClose={() => setIsExcelUploadDialogOpen(false)}
        onSuccess={handleExcelUploadSuccess}
      />

      {/* Add Department Dialog */}
      <AddDepartmentDialog
        isOpen={isAddDepartmentDialogOpen}
        onClose={() => {
          setIsAddDepartmentDialogOpen(false);
          setAddDepartmentContext(null);
        }}
        onSuccess={handleDepartmentCreated}
        unitContext={addDepartmentContext}
      />

      {/* Edit Department Dialog */}
      <EditDepartmentDialog
        isOpen={isEditDepartmentDialogOpen}
        onClose={() => {
          setIsEditDepartmentDialogOpen(false);
          setEditingDepartment(null);
        }}
        onSuccess={handleDepartmentUpdated}
        department={editingDepartment}
      />

      {/* Edit Unit Dialog */}
      <UnitDialog
        unit={editingUnit}
        isOpen={isEditUnitDialogOpen}
        onClose={() => {
          setIsEditUnitDialogOpen(false);
          setEditingUnit(null);
        }}
        onSuccess={handleUnitUpdated}
        mode="edit"
      />
      
      {/* Delete Confirmation Dialog */}
      <ConfirmationDialog
        isOpen={isDeleteConfirmOpen}
        title="Delete Contact"
        message={contactToDelete ? 
          `Are you sure you want to delete ${contactToDelete.name || contactToDelete.designation || contactToDelete.service_no || 'this contact'}? This action cannot be undone.` :
          'Are you sure you want to delete this contact?'
        }
        confirmText="Delete"
        cancelText="Cancel"
        onConfirm={confirmDeleteContact}
        onClose={cancelDeleteContact}
        type="danger"
      />
      
      {/* Department Delete Confirmation Dialog */}
      <ConfirmationDialog
        isOpen={isDepartmentDeleteConfirmOpen}
        title="Delete Department"
        message={departmentToDelete ? 
          `Are you sure you want to delete the department "${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"
      />
      
      {/* Unit Delete Confirmation Dialog */}
      <ConfirmationDialog
        isOpen={isUnitDeleteConfirmOpen}
        title="Delete Unit"
        message={unitToDelete ? 
          `Are you sure you want to delete the unit "${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"
      />
      
      {/* Toast Notifications */}
      <ToastContainer />
    </div>
  );
};

export default Directory;
