import React, { useState, useEffect } from 'react';
import { X, MessageCircle, Phone, Mail, Save, Edit, Plus, Key, Facebook, Linkedin, MapPin, Map, Briefcase } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { User } from '../../types';
import { organizationalApi, departmentsApi, designationsApi, contactApi, Unit, Designation } from '../../services/api';
import { useAuth } from '../../context/AuthContext';
import CreateDesignationModal from './CreateDesignationModal';

interface ContactDialogProps {
  user: User | null;
  isOpen: boolean;
  onClose: () => void;
  onMessage?: (user: User) => void;
  onCall: (user: User) => void;
  onSMS: (user: User) => void;
  onCreate?: (contactData: any) => void;
  onUpdate?: (contactData: any) => void;
  onChangePassword?: (userId: number, newPassword: string) => void;
  mode?: 'view' | 'create' | 'edit';
  // Context for auto-selecting unit and department in create mode
  defaultUnitName?: string;
  defaultDepartmentName?: string;
  // Additional props for create mode
  parentUser?: User | null;
  availableUsers?: User[];
}

const ContactDialog: React.FC<ContactDialogProps> = ({
  user,
  isOpen,
  onClose,
  onMessage,
  onCall,
  onSMS,
  onCreate,
  onUpdate,
  onChangePassword,
  mode = 'view',
  defaultUnitName,
  defaultDepartmentName,
  parentUser,
  availableUsers
}) => {
  const navigate = useNavigate();
  const { hasAnyPermission, isSuperAdmin } = useAuth();
  const [units, setUnits] = useState<Unit[]>([]);
  const [departments, setDepartments] = useState<any[]>([]);
  const [designations, setDesignations] = useState<Designation[]>([]);
  const [filteredDesignations, setFilteredDesignations] = useState<Designation[]>([]);
  const [dataLoading, setDataLoading] = useState(false);
  const [isCreateDesignationModalOpen, setIsCreateDesignationModalOpen] = useState(false);
  const [isChangePasswordModalOpen, setIsChangePasswordModalOpen] = useState(false);
  const [newPassword, setNewPassword] = useState('');

  const [formData, setFormData] = useState({
    phone: '',
    mobile: '',
    alternative_mobile: '',
    email: '',
    organization: '',
    designation: '',
    organization_id: null,
    occupation: '',
    facebook: '',
    linkedin: '',
    present_address: '',
    present_lat_lng: '',
    office_address: '',
    office_lat_lng: '',
    permanent_address: '',
    permanent_lat_lng: '',
    order_id: null as number | null,
    is_active: true,
    time: '',
    designation_id: null as number | null,
    unit_id: null as number | null,
    department_id: null as number | null
  });

  // Reset form to initial state
  const resetForm = () => {
    setFormData({
      phone: '',
      mobile: '',
      alternative_mobile: '',
      email: '',
      organization: '',
      organization_id: null,
      designation: '',
      occupation: '',
      facebook: '',
      linkedin: '',
      present_address: '',
      present_lat_lng: '',
      office_address: '',
      office_lat_lng: '',
      permanent_address: '',
      permanent_lat_lng: '',
      order_id: null,
      is_active: true,
      time: '',
      designation_id: null,
      unit_id: null,
      department_id: null
    });
  };

  useEffect(() => {
    if (user && mode !== 'create') {
      setFormData({
        phone: user.phone,
        mobile: user.mobile || '',
        alternative_mobile: user.alternative_mobile || '',
        email: user.email,
        organization: user.organization || '',
        organization_id: user.organization_id || null,
        designation: user.designation || '',
        occupation: user.occupation || '',
        facebook: user.facebook || '',
        linkedin: user.linkedin || '',
        present_address: user.present_address || '',
        present_lat_lng: user.present_lat_lng || '',
        office_address: user.office_address || '',
        office_lat_lng: user.office_lat_lng || '',
        permanent_address: user.permanent_address || '',
        permanent_lat_lng: user.permanent_lat_lng || '',
        order_id: user.order_id ? Number(user.order_id) : null,
        is_active: user.is_active !== undefined ? (Number(user.is_active) === 1 || user.is_active === true) : true,
        time: user.time || '',
        designation_id: null, // Will need to be set based on designation name lookup
        unit_id: null, // Will need to be set based on unit name lookup
        department_id: null // Will need to be set based on department name lookup
      });
    } else if (mode === 'create') {
      setFormData({
        phone: '',
        mobile: '',
        alternative_mobile: '',
        email: '',
        organization: '',
        organization_id: null,
        designation: '',
        occupation: '',
        facebook: '',
        linkedin: '',
        present_address: '',
        present_lat_lng: '',
        office_address: '',
        office_lat_lng: '',
        permanent_address: '',
        permanent_lat_lng: '',
        order_id: null,
        is_active: true,
        time: '',
        designation_id: null,
        unit_id: null, // Will be auto-selected based on defaultUnitName or parentUser
        department_id: null // Will be auto-selected based on defaultDepartmentName or parentUser
      });
    }
  }, [user, mode]);

  // Load full contact from API for edit mode to ensure all fields are present
  useEffect(() => {
    const fetchFullContact = async () => {
      if (!user || mode !== 'edit') return;
      try {
        const resp = await contactApi.getContact(user.id);
        if (resp.status === 'success' && resp.data && resp.data.contact) {
          const c = resp.data.contact as any;
          setFormData(prev => ({
            ...prev,
            occupation: c.occupation || prev.occupation,
            organization: c.organization || prev.organization,
            facebook: c.facebook || prev.facebook,
            linkedin: c.linkedin || prev.linkedin,
            present_lat_lng: c.present_lat_lng || prev.present_lat_lng,
            office_lat_lng: c.office_lat_lng || prev.office_lat_lng,
            permanent_lat_lng: c.permanent_lat_lng || prev.permanent_lat_lng,
            present_address: c.present_address || prev.present_address,
            office_address: c.office_address || prev.office_address,
            permanent_address: c.permanent_address || prev.permanent_address,
            organization_id: c.organization_id ? Number(c.organization_id) : prev.organization_id,
            order_id: c.order_id ? Number(c.order_id) : prev.order_id
          }));
        }
      } catch (err) {
        console.error('Failed to fetch full contact for edit:', err);
      }
    };
    fetchFullContact();
  }, [user, mode]);

  // Helper functions to find IDs by names
  const findUnitIdByName = (unitName: string) => {
    const unit = units.find(u => u.name === unitName);
    return unit ? unit.id : null;
  };

  const findDepartmentIdByName = (departmentName: string) => {
    const department = departments.find(d => d.name === departmentName);
    return department ? department.id : null;
  };

  const findDesignationIdByName = (designationName: string) => {
    // First try to find in filteredDesignations (for current department)
    let designation = filteredDesignations.find(d => d.name === designationName);
    
    // If not found, try in all designations
    if (!designation) {
      designation = designations.find(d => d.name === designationName);
    }
    
    return designation ? designation.id : null;
  };

  // Load designations by department
  const loadDesignationsByDepartment = async (departmentId: number | null) => {
    if (!departmentId) {
      setFilteredDesignations([]);
      return;
    }

    try {
      const response = await designationsApi.getDesignationsByDepartment(departmentId);
      if (response.status === 'success' && response.data) {
        setFilteredDesignations(response.data);
      } else {
        console.error('Failed to load designations by department:', response.message);
        setFilteredDesignations([]);
      }
    } catch (error) {
      console.error('Error loading designations by department:', error);
      setFilteredDesignations([]);
    }
  };


  // Update form data with IDs when user data changes and dropdown data is loaded
  useEffect(() => {
    if (user && mode !== 'create' && units.length > 0 && departments.length > 0) {
      const unitId = findUnitIdByName(user.unit);
      const departmentId = findDepartmentIdByName(user.department || '');
      
      setFormData(prev => ({
        ...prev,
        unit_id: unitId,
        department_id: departmentId,
        designation_id: null // Will be set after designations are loaded
      }));
      
      // Load designations for the department first, then set designation
      if (departmentId) {
        loadDesignationsByDepartment(departmentId).then(() => {
          // After designations are loaded, find and set the designation ID
          const designationId = findDesignationIdByName(user.designation);
          if (designationId) {
            setFormData(prev => ({
              ...prev,
              designation_id: designationId
            }));
          }
        });
      }
    }
  }, [user, mode, units, departments]);

  // Auto-select unit and department for create mode
  useEffect(() => {
    if (mode === 'create' && units.length > 0 && departments.length > 0) {
      if (defaultUnitName && defaultDepartmentName) {
        // Use provided default values
        const unitId = findUnitIdByName(defaultUnitName);
        const departmentId = findDepartmentIdByName(defaultDepartmentName);
        
        if (unitId && departmentId) {
          setFormData(prev => ({
            ...prev,
            unit_id: unitId,
            department_id: departmentId
          }));
        }
      } else {
        // Fallback: select first available unit and department
        const firstUnit = units[0];
        const firstDepartment = departments[0];
        
        if (firstUnit && firstDepartment) {
          setFormData(prev => ({
            ...prev,
            unit_id: firstUnit.id,
            department_id: firstDepartment.id
          }));
        }
      }
    }
  }, [mode, units, departments, defaultUnitName, defaultDepartmentName]);


  // Load designations when department changes
  useEffect(() => {
    if (formData.department_id) {
      loadDesignationsByDepartment(formData.department_id);
      // Reset designation when department changes
      setFormData(prev => ({
        ...prev,
        designation_id: null
      }));
    } else {
      setFilteredDesignations([]);
    }
  }, [formData.department_id]);

  // Load dropdown data when dialog opens
  useEffect(() => {
    if (isOpen && (mode === 'create' || mode === 'edit')) {
      loadDropdownData();
    }
  }, [isOpen, mode]);

  const loadDropdownData = async () => {
    setDataLoading(true);
    try {
      const [unitsResponse, departmentsResponse, designationsResponse] = await Promise.all([
        organizationalApi.getUnits({ tree: false }),
        departmentsApi.getDepartmentsForDropdown(),
        designationsApi.getDesignationsForDropdown()
      ]);

      console.log('API Responses:', {
        units: unitsResponse,
        departments: departmentsResponse,
        designations: designationsResponse
      });

      if (unitsResponse.status === 'success' && unitsResponse.data) {
        setUnits(unitsResponse.data.units.sort((a, b) => a.id - b.id));
      }

      if (departmentsResponse.status === 'success' && departmentsResponse.data) {
        setDepartments(departmentsResponse.data);
      }

      if (designationsResponse.status === 'success' && designationsResponse.data) {
        setDesignations(designationsResponse.data);
      }

    } catch (error) {
      console.error('Failed to load dropdown data:', error);
    } finally {
      setDataLoading(false);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: name.includes('_id') ? (value === '' ? null : parseInt(value)) : value
    }));
  };


  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // Clean up form data - set empty strings to null for mobile fields
    const cleanedFormData: any = {
      ...formData,
      mobile: formData.mobile.trim() === '' ? null : formData.mobile.trim(),
      alternative_mobile: formData.alternative_mobile.trim() === '' ? null : formData.alternative_mobile.trim(),
      organization: formData.organization.trim() === '' ? null : formData.organization.trim(),
      designation: formData.designation.trim() === '' ? null : formData.designation.trim(),
      occupation: formData.occupation.trim() === '' ? null : formData.occupation.trim(),
      facebook: formData.facebook.trim() === '' ? null : formData.facebook.trim(),
      linkedin: formData.linkedin.trim() === '' ? null : formData.linkedin.trim(),
      present_address: formData.present_address.trim() === '' ? null : formData.present_address.trim(),
      present_lat_lng: formData.present_lat_lng.trim() === '' ? null : formData.present_lat_lng.trim(),
      office_address: formData.office_address.trim() === '' ? null : formData.office_address.trim(),
      office_lat_lng: formData.office_lat_lng.trim() === '' ? null : formData.office_lat_lng.trim(),
      permanent_address: formData.permanent_address.trim() === '' ? null : formData.permanent_address.trim(),
      permanent_lat_lng: formData.permanent_lat_lng.trim() === '' ? null : formData.permanent_lat_lng.trim(),
      time: formData.time.trim() === '' ? null : formData.time.trim()
    };

    // Normalize numeric IDs safely
    cleanedFormData.organization_id = typeof formData.organization_id === 'number' ? formData.organization_id : null;
    cleanedFormData.designation_id = typeof formData.designation_id === 'number' ? formData.designation_id : null;
    cleanedFormData.unit_id = typeof formData.unit_id === 'number' ? formData.unit_id : null;
    cleanedFormData.department_id = typeof formData.department_id === 'number' ? formData.department_id : null;
    cleanedFormData.order_id = typeof formData.order_id === 'number' ? formData.order_id : null;

    // In create mode, add unit_id and department_id from context or defaults
    if (mode === 'create') {
      // Find unit and department IDs by name if not already set
      if (!cleanedFormData.unit_id && defaultUnitName) {
        cleanedFormData.unit_id = findUnitIdByName(defaultUnitName);
      }
      if (!cleanedFormData.department_id && defaultDepartmentName) {
        cleanedFormData.department_id = findDepartmentIdByName(defaultDepartmentName);
      }
    }
    
    if (mode === 'create' && onCreate) {
      onCreate(cleanedFormData);
      // Reset form after successful creation
      resetForm();
    } else if (mode === 'edit' && onUpdate) {
      onUpdate(cleanedFormData);
    }
  };

  const handleMessageClick = (user: User) => {
    // Close the dialog first
    onClose();
    
    // Navigate to individual messaging page with user data
    navigate('/individual-messaging', {
      state: {
        recipientUser: user
      }
    });
  };

  const handleDesignationCreated = async () => {
    // Refresh designations for the current department
    if (formData.department_id) {
      await loadDesignationsByDepartment(formData.department_id);
    }
    // Also refresh all designations
    const response = await designationsApi.getDesignationsForDropdown();
    if (response.status === 'success' && response.data) {
      setDesignations(response.data);
    }
  };

  const handleChangePassword = () => {
    setIsChangePasswordModalOpen(true);
    setNewPassword('');
  };

  const confirmChangePassword = () => {
    if (!user || !newPassword.trim()) return;
    
    console.log('🔐 ContactDialog: Confirming password change for user:', user.id, 'Name:', user.name);
    
    if (onChangePassword) {
      onChangePassword(user.id, newPassword.trim());
    }
    
    setIsChangePasswordModalOpen(false);
    setNewPassword('');
  };

  const cancelChangePassword = () => {
    setIsChangePasswordModalOpen(false);
    setNewPassword('');
  };

  if (!isOpen) return null;


  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl shadow-2xl max-w-md w-full mx-4 max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-xl font-semibold text-gray-900">
            {mode === 'create' ? 'Create New Contact' : 
             mode === 'edit' ? 'Edit Contact' : 'Contact Details'}
          </h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-full transition-colors"
          >
            <X className="h-5 w-5 text-gray-500" />
          </button>
        </div>

        {/* Content */}
        {mode === 'view' && user ? (
          <div className="p-6">
            <div className="flex items-center space-x-4 mb-6">
              {/* Avatar - Dynamic Permission Check */}
              {(isSuperAdmin() || hasAnyPermission(['contact.details.name', 'contact.details.designation'])) && (
                <div className="w-16 h-16 bg-blue-600 rounded-full flex items-center justify-center text-white font-semibold text-lg">
                  {user.designation.split(' ').map(n => n[0]).join('').slice(0, 2)}
                </div>
              )}
              
              <div className="flex-1">
                {/* Designation - Dynamic Permission Check */}
                {(isSuperAdmin() || hasAnyPermission(['contact.details.designation'])) && (
                  <h3 className="text-lg font-semibold text-gray-900">{user.designation}</h3>
                )}
                {/* <p className="text-sm text-gray-600">ID No: {user.service_no}</p> */}
              </div>
            </div>

            {/* Contact Details */}
            <div className="space-y-3 mb-6">
              {/* Phone - Dynamic Permission Check */}
              {(isSuperAdmin() || hasAnyPermission(['contact.details.phone'])) && (
                <div className="flex items-center space-x-3"> 
                  <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
                    <Phone className="h-4 w-4 text-gray-600" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-900">Phone</p>
                    <p className="text-sm text-gray-600">{user.phone}</p>
                  </div>
                </div>
              )}

              {/* Mobile - Dynamic Permission Check */}
              {user.mobile && (isSuperAdmin() || hasAnyPermission(['contact.details.mobile'])) && (
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
                    <Phone className="h-4 w-4 text-gray-600" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-900">Mobile</p>
                    <p className="text-sm text-gray-600">{user.mobile}</p>
                  </div>
                </div>
              )}

              {/* Alternative Mobile - Dynamic Permission Check */}
              {user.alternative_mobile && (isSuperAdmin() || hasAnyPermission(['contact.details.alternative_mobile'])) && (
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
                    <Phone className="h-4 w-4 text-gray-600" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-900">Alternative Mobile</p>
                    <p className="text-sm text-gray-600">{user.alternative_mobile}</p>
                  </div>
                </div>
              )}

              {/* Email - Dynamic Permission Check */}
              {(isSuperAdmin() || hasAnyPermission(['contact.details.email'])) && (
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
                    <Mail className="h-4 w-4 text-gray-600" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-900">Email</p>
                    <p className="text-sm text-gray-600">{user.email}</p>
                  </div>
                </div>
              )}

              {/* Occupation - Dynamic Permission Check */}
              {user.occupation && (isSuperAdmin() || hasAnyPermission(['contact.details.occupation'])) && (
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
                    <span className="text-xs text-gray-600">Occ</span>
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-900">Occupation</p>
                    <p className="text-sm text-gray-600">{user.occupation}</p>
                  </div>
                </div>
              )}

              {/* Order ID - Dynamic Permission Check */}
              {(isSuperAdmin() || hasAnyPermission(['contact.details.order_id'])) && (
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
                    <span className="text-xs text-gray-600">OID</span>
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-900">Order ID</p>
                    <p className="text-sm text-gray-600">{user.order_id || 'Not provided'}</p>
                  </div>
                </div>
              )}

              {/* Time - Dynamic Permission Check */}
              {(isSuperAdmin() || hasAnyPermission(['contact.details.time'])) && (
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
                    <span className="text-xs text-gray-600">Time</span>
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-900">Time</p>
                    <p className="text-sm text-gray-600">{user.time || 'Not provided'}</p>
                  </div>
                </div>
              )}

              {/* Facebook - Dynamic Permission Check */}
              {user.facebook && (isSuperAdmin() || hasAnyPermission(['contact.details.facebook'])) && (
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
                    <Facebook className="h-4 w-4 text-gray-600" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-900">Facebook</p>
                    <a href={user.facebook} target="_blank" rel="noopener noreferrer" className="text-sm text-blue-600 hover:underline">{user.facebook}</a>
                  </div>
                </div>
              )}

              {/* LinkedIn - Dynamic Permission Check */}
              {user.linkedin && (isSuperAdmin() || hasAnyPermission(['contact.details.linkedin'])) && (
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
                    <Linkedin className="h-4 w-4 text-gray-600" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-900">LinkedIn</p>
                    <a href={user.linkedin} target="_blank" rel="noopener noreferrer" className="text-sm text-blue-600 hover:underline">{user.linkedin}</a>
                  </div>
                </div>
              )}
            </div>
          </div>
        ) : (
          <form id="contact-form" onSubmit={handleSubmit} className="p-6">
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Phone *</label>
                <input
                  type="tel"
                  name="phone"
                  value={formData.phone}
                  onChange={handleInputChange}
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Mobile</label>
                <input
                  type="tel"
                  name="mobile"
                  value={formData.mobile}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Alternative Mobile</label>
                <input
                  type="tel"
                  name="alternative_mobile"
                  value={formData.alternative_mobile}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Email *</label>
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleInputChange}
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Organization</label>
                <input
                  type="text"
                  name="organization"
                  value={formData.organization}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Occupation</label>
                <input
                  type="text"
                  name="occupation"
                  value={formData.occupation}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Facebook URL</label>
                <input
                  type="url"
                  name="facebook"
                  value={formData.facebook}
                  onChange={handleInputChange}
                  placeholder="https://facebook.com/username"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">LinkedIn URL</label>
                <input
                  type="url"
                  name="linkedin"
                  value={formData.linkedin}
                  onChange={handleInputChange}
                  placeholder="https://linkedin.com/in/username"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Designation (Text)</label>
                <input
                  type="text"
                  name="designation"
                  value={formData.designation}
                  onChange={handleInputChange}
                  placeholder="e.g., Flag Lt"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* Address Fields - Beautifully Styled Separate Sections */}
              <div className="mt-4 space-y-4">
                {/* Present Address Section */}
                <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl p-4 border border-blue-100 shadow-sm hover:shadow-md transition-shadow">
                  <div className="flex items-center mb-3">
                    <div className="bg-blue-100 rounded-lg p-2 mr-3">
                      <MapPin className="h-5 w-5 text-blue-600" />
                    </div>
                    <h3 className="text-base font-semibold text-gray-800 flex-1">
                      Present Address
                    </h3>
                  </div>
                  <div className="space-y-3">
                    <div>
                      <input
                        type="text"
                        name="present_address"
                        value={formData.present_address}
                        onChange={handleInputChange}
                        placeholder="House/Road, City, District"
                        className="w-full px-4 py-2.5 bg-white border border-blue-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-400 transition-all"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-600 mb-1.5">Coordinates (Lat, Lng)</label>
                      <input
                        type="text"
                        name="present_lat_lng"
                        value={formData.present_lat_lng}
                        onChange={handleInputChange}
                        placeholder="23.8103,90.4125"
                        className="w-full px-4 py-2 bg-white border border-blue-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-400 transition-all text-sm"
                      />
                    </div>
                  </div>
                </div>

                {/* Office Address Section */}
                <div className="bg-gradient-to-r from-purple-50 to-pink-50 rounded-xl p-4 border border-purple-100 shadow-sm hover:shadow-md transition-shadow">
                  <div className="flex items-center mb-3">
                    <div className="bg-purple-100 rounded-lg p-2 mr-3">
                      <Briefcase className="h-5 w-5 text-purple-600" />
                    </div>
                    <h3 className="text-base font-semibold text-gray-800 flex-1">
                      Office Address
                    </h3>
                  </div>
                  <div className="space-y-3">
                    <div>
                      <input
                        type="text"
                        name="office_address"
                        value={formData.office_address}
                        onChange={handleInputChange}
                        placeholder="Office Building, Street, City"
                        className="w-full px-4 py-2.5 bg-white border border-purple-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-purple-400 transition-all"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-600 mb-1.5">Coordinates (Lat, Lng)</label>
                      <input
                        type="text"
                        name="office_lat_lng"
                        value={formData.office_lat_lng}
                        onChange={handleInputChange}
                        placeholder="23.8103,90.4125"
                        className="w-full px-4 py-2 bg-white border border-purple-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-purple-400 transition-all text-sm"
                      />
                    </div>
                  </div>
                </div>

                {/* Permanent Address Section */}
                <div className="bg-gradient-to-r from-green-50 to-emerald-50 rounded-xl p-4 border border-green-100 shadow-sm hover:shadow-md transition-shadow">
                  <div className="flex items-center mb-3">
                    <div className="bg-green-100 rounded-lg p-2 mr-3">
                      <Map className="h-5 w-5 text-green-600" />
                    </div>
                    <h3 className="text-base font-semibold text-gray-800 flex-1">
                      Permanent Address
                    </h3>
                  </div>
                  <div className="space-y-3">
                    <div>
                      <input
                        type="text"
                        name="permanent_address"
                        value={formData.permanent_address}
                        onChange={handleInputChange}
                        placeholder="Village/Area, District, Division"
                        className="w-full px-4 py-2.5 bg-white border border-green-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-400 transition-all"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-600 mb-1.5">Coordinates (Lat, Lng)</label>
                      <input
                        type="text"
                        name="permanent_lat_lng"
                        value={formData.permanent_lat_lng}
                        onChange={handleInputChange}
                        placeholder="23.8103,90.4125"
                        className="w-full px-4 py-2 bg-white border border-green-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-400 transition-all text-sm"
                      />
                    </div>
                  </div>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Order ID</label>
                <input
                  type="number"
                  name="order_id"
                  value={formData.order_id ?? ''}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div className="flex items-center mt-6">
                <input
                  type="checkbox"
                  name="is_active"
                  id="is_active"
                  checked={!!formData.is_active}
                  onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
                  className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
                <label htmlFor="is_active" className="ml-2 block text-sm text-gray-900">
                  Active
                </label>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Time</label>
                <input
                  type="text"
                  name="time"
                  value={formData.time}
                  onChange={handleInputChange}
                  placeholder="e.g. 09:00 AM"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* Unit and Department fields - show in both edit and create mode */}
              {(mode === 'edit' || mode === 'create') && (
                <>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Unit *</label>
                    <select
                      name="unit_id"
                      value={formData.unit_id || ''}
                      onChange={handleInputChange}
                      required
                      disabled={dataLoading}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
                    >
                      <option value="">Select Unit</option>
                      {units.map(unit => (
                        <option key={unit.id} value={unit.id}>{unit.name}</option>
                      ))}
                    </select>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Department *</label>
                    <select
                      name="department_id"
                      value={formData.department_id || ''}
                      onChange={handleInputChange}
                      required
                      disabled={dataLoading}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
                    >
                      <option value="">Select Department</option>
                      {departments.map(department => (
                        <option key={department.id} value={department.id}>{department.name}</option>
                      ))}
                    </select>
                  </div>
                </>
              )}

              {/* Show helpful info in create mode */}
              {mode === 'create' && (
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                  <p className="text-sm text-blue-800">
                    <span className="font-medium">Note:</span> Please select the appropriate unit, department, and designation for the new contact.
                  </p>
                </div>
              )}

              <div>
                <div className="flex items-center justify-between mb-1">
                  <label className="block text-sm font-medium text-gray-700">Designation *</label>
                  {(isSuperAdmin() || hasAnyPermission(['designation.create'])) && (
                    <button
                      type="button"
                      onClick={() => setIsCreateDesignationModalOpen(true)}
                      disabled={!formData.department_id}
                      className="flex items-center space-x-1 text-blue-600 hover:text-blue-700 text-sm font-medium transition-colors disabled:text-gray-400 disabled:cursor-not-allowed"
                      title={!formData.department_id ? "Please select a department first" : "Create New Designation"}
                    >
                      <Plus className="h-4 w-4" />
                      <span>Add</span>
                    </button>
                  )}
                </div>
                <select
                  name="designation_id"
                  value={formData.designation_id || ''}
                  onChange={handleInputChange}
                  required
                  disabled={dataLoading || !formData.department_id}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
                >
                  <option value="">
                    {!formData.department_id ? 'Select Department First' : 'Select Designation'}
                  </option>
                  {filteredDesignations.map(designation => (
                    <option key={designation.id} value={designation.id}>{designation.name}</option>
                  ))}
                </select>
                {!formData.department_id && (
                  <p className="text-xs text-gray-500 mt-1">
                    Please select a department first to see available designations.
                  </p>
                )}
              </div>

            </div>
          </form>
        )}

        {/* Action Buttons */}
        <div className="flex space-x-3 p-6 border-t border-gray-200">
          {mode === 'view' && user ? (
            <>
              {/* Message Button - Dynamic Permission Check */}
              {(isSuperAdmin() || hasAnyPermission(['contact.details.message'])) && (
                <button
                  className="flex-1 flex items-center justify-center space-x-2 bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 transition-colors"
                  onClick={() => handleMessageClick(user)}
                >
                  <MessageCircle className="h-5 w-5" />
                  <span>Message</span>
                </button>
              )}
              
              {/* Call Button - Dynamic Permission Check */}
              {(isSuperAdmin() || hasAnyPermission(['contact.details.call'])) && (
                <button
                  className="flex-1 flex items-center justify-center space-x-2 bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 transition-colors"
                  onClick={() => onCall(user)}
                >
                  <Phone className="h-5 w-5" />
                  <span>Call</span>
                </button>
              )}
              
              {/* SMS Button - Dynamic Permission Check */}
              {(isSuperAdmin() || hasAnyPermission(['contact.details.sms'])) && (
                <button
                  className="flex-1 flex items-center justify-center space-x-2 bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 transition-colors"
                  onClick={() => onSMS(user)}
                >
                  <Mail className="h-5 w-5" />
                  <span>SMS</span>
                </button>
              )}
              
              {/* Edit Button - Dynamic Permission Check */}
              {onUpdate && (isSuperAdmin() || hasAnyPermission(['contact.details.edit'])) && (
                <button
                  className="flex-1 flex items-center justify-center space-x-2 bg-orange-600 text-white py-3 px-4 rounded-lg hover:bg-orange-700 transition-colors"
                  onClick={() => {
                    // Switch to edit mode
                    const event = new CustomEvent('contactEdit', { detail: user });
                    window.dispatchEvent(event);
                  }}
                >
                  <Edit className="h-5 w-5" />
                  <span>Edit</span>
                </button>
              )}
              
              {/* Change Password Button - Dynamic Permission Check */}
              {onChangePassword && (isSuperAdmin() || hasAnyPermission(['contact.details.edit'])) && (
                <button
                  className="flex-1 flex items-center justify-center space-x-2 bg-red-600 text-white py-3 px-4 rounded-lg hover:bg-red-700 transition-colors"
                  onClick={handleChangePassword}
                >
                  <Key className="h-5 w-5" />
                  <span>Change Password</span>
                </button>
              )}
            </>
          ) : (
            <>
              <button
                type="button"
                onClick={onClose}
                className="flex-1 flex items-center justify-center space-x-2 bg-gray-600 text-white py-3 px-4 rounded-lg hover:bg-gray-700 transition-colors"
              >
                <X className="h-5 w-5" />
                <span>Cancel</span>
              </button>
              
              <button
                type="submit"
                form="contact-form"
                className="flex-1 flex items-center justify-center space-x-2 bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 transition-colors"
              >
                <Save className="h-5 w-5" />
                <span>{mode === 'create' ? 'Create' : 'Update'}</span>
              </button>
            </>
          )}
        </div>
        
        {/* Loading overlay for data loading */}
        {dataLoading && (
          <div className="absolute inset-0 bg-white bg-opacity-75 flex items-center justify-center">
            <div className="text-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2"></div>
              <p className="text-gray-600 text-sm">Loading data...</p>
            </div>
          </div>
        )}
      </div>

      {/* Create Designation Modal */}
      <CreateDesignationModal
        isOpen={isCreateDesignationModalOpen}
        onClose={() => setIsCreateDesignationModalOpen(false)}
        onSuccess={handleDesignationCreated}
        defaultDepartmentId={formData.department_id || undefined}
        defaultDepartmentName={departments.find(d => d.id === formData.department_id)?.name}
      />

      {/* Change Password Modal */}
      {isChangePasswordModalOpen && (
        <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">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-gray-900">Change Password</h3>
              <button
                onClick={cancelChangePassword}
                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: {user?.name}
                </label>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Service No: {user?.service_no}
                </label>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  New Password *
                </label>
                <input
                  type="password"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  placeholder="Enter new password"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
                />
              </div>
              
              <div className="flex space-x-3 pt-4">
                <button
                  onClick={cancelChangePassword}
                  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={confirmChangePassword}
                  disabled={!newPassword.trim()}
                  className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Change Password
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ContactDialog;
