import React, { useState, useEffect } from 'react';
import { X, Save, User as UserIcon, Phone, Mail, Building, Award, Briefcase } from 'lucide-react';
import { organizationalApi, departmentsApi, designationsApi, ranksApi, generateServiceNumber, contactApi } from '../../services/api';
import { Unit, Designation, Rank } from '../../services/api';
import { Department } from '../../types';

interface AddUserDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const AddUserDialog: React.FC<AddUserDialogProps> = ({
  isOpen,
  onClose,
  onSuccess
}) => {
  const [formData, setFormData] = useState({
    name: '',
    service_no: '',
    phone: '',
    email: '',
    unit_id: '',
    department_id: '',
    designation_id: '',
    rank_id: '',
    parent_id: null as number | null
  });

  const [units, setUnits] = useState<Unit[]>([]);
  const [departments, setDepartments] = useState<Department[]>([]);
  const [designations, setDesignations] = useState<Designation[]>([]);
  const [ranks, setRanks] = useState<Rank[]>([]);
  
  const [loading, setLoading] = useState(false);
  const [dataLoading, setDataLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Load data when dialog opens
  useEffect(() => {
    if (isOpen) {
      loadData();
      // Auto-generate service number
      generateServiceNumber().then(serviceNo => {
        setFormData(prev => ({
          ...prev,
          service_no: serviceNo
        }));
      });
    }
  }, [isOpen]);

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

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

      if (unitsResponse.status === 'success' && unitsResponse.data) {
        setUnits(unitsResponse.data.units.sort((a, b) => a.id - b.id));
        console.log('Units loaded:', unitsResponse.data.units.length);
      }

      if (departmentsResponse.status === 'success' && departmentsResponse.data) {
        setDepartments(departmentsResponse.data);
        console.log('Departments loaded:', departmentsResponse.data.length);
      }

      if (designationsResponse.status === 'success' && designationsResponse.data) {
        setDesignations(designationsResponse.data);
        console.log('Designations loaded:', designationsResponse.data.length);
      } else {
        console.error('Designations response error:', designationsResponse);
      }

      if (ranksResponse.status === 'success' && ranksResponse.data) {
        setRanks(ranksResponse.data);
        console.log('Ranks loaded:', ranksResponse.data.length);
      } else {
        console.error('Ranks response error:', ranksResponse);
      }
    } catch (error) {
      console.error('Failed to load data:', error);
      setError(error instanceof Error ? error.message : 'Failed to load data');
    } finally {
      setDataLoading(false);
    }
  };

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      // Prepare the request body according to the API specification
      const contactData = {
        name: formData.name,
        service_no: formData.service_no,
        unit_id: parseInt(formData.unit_id),
        department_id: parseInt(formData.department_id),
        designation_id: parseInt(formData.designation_id),
        phone: formData.phone,
        email: formData.email,
        parent_id: formData.parent_id || undefined,
        rank_id: parseInt(formData.rank_id)
      };

      const response = await contactApi.createContact(contactData);
      
      if (response.status === 'success') {
        onSuccess();
        onClose();
        // Reset form
        const newServiceNo = await generateServiceNumber();
        setFormData({
          name: '',
          service_no: newServiceNo,
          phone: '',
          email: '',
          unit_id: '',
          department_id: '',
          designation_id: '',
          rank_id: '',
          parent_id: null
        });
      } else {
        setError(response.message || 'Failed to create contact');
      }
    } catch (error) {
      console.error('Failed to create contact:', error);
      setError(error instanceof Error ? error.message : 'Failed to create contact');
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    if (!loading) {
      onClose();
      setError(null);
    }
  };

  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">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center">
              <UserIcon className="h-5 w-5 text-white" />
            </div>
            <h2 className="text-xl font-semibold text-gray-900">Add New User</h2>
          </div>
          <button
            onClick={handleClose}
            disabled={loading}
            className="p-2 hover:bg-gray-100 rounded-full transition-colors disabled:opacity-50"
          >
            <X className="h-5 w-5 text-gray-500" />
          </button>
        </div>

        {/* Content */}
        <form onSubmit={handleSubmit} className="p-6">
          {error && (
            <div className="mb-4 p-3 bg-red-100 border border-red-300 rounded-lg">
              <p className="text-red-700 text-sm">{error}</p>
            </div>
          )}

          <div className="space-y-4">
            {/* Name */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                <UserIcon className="h-4 w-4 inline mr-1" />
                Name *
              </label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleInputChange}
                required
                disabled={loading}
                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"
                placeholder="Enter full name"
              />
            </div>

            {/* Service Number */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                <Briefcase className="h-4 w-4 inline mr-1" />
                Service Number *
              </label>
              <input
                type="text"
                name="service_no"
                value={formData.service_no}
                onChange={handleInputChange}
                required
                disabled={loading}
                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 bg-gray-50"
                placeholder="Auto-generated"
              />
              <p className="text-xs text-gray-500 mt-1">Service number is auto-generated</p>
            </div>

            {/* Phone */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                <Phone className="h-4 w-4 inline mr-1" />
                Phone *
              </label>
              <input
                type="tel"
                name="phone"
                value={formData.phone}
                onChange={handleInputChange}
                required
                disabled={loading}
                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"
                placeholder="+880123456789"
              />
            </div>

            {/* Email */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                <Mail className="h-4 w-4 inline mr-1" />
                Email *
              </label>
              <input
                type="email"
                name="email"
                value={formData.email}
                onChange={handleInputChange}
                required
                disabled={loading}
                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"
                placeholder="user@example.com"
              />
            </div>

            {/* Unit */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                <Building className="h-4 w-4 inline mr-1" />
                Unit *
              </label>
              <select
                name="unit_id"
                value={formData.unit_id}
                onChange={handleInputChange}
                required
                disabled={loading || 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>

            {/* Department */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                <Building className="h-4 w-4 inline mr-1" />
                Department *
              </label>
              <select
                name="department_id"
                value={formData.department_id}
                onChange={handleInputChange}
                required
                disabled={loading || 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>

            {/* Designation */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                <Briefcase className="h-4 w-4 inline mr-1" />
                Designation * ({designations.length} available)
              </label>
              <select
                name="designation_id"
                value={formData.designation_id}
                onChange={handleInputChange}
                required
                disabled={loading || 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 Designation</option>
                {designations.map(designation => (
                  <option key={designation.id} value={designation.id}>{designation.name}</option>
                ))}
              </select>
              {designations.length === 0 && !dataLoading && (
                <p className="text-red-500 text-xs mt-1">No designations available</p>
              )}
            </div>

            {/* Rank */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                <Award className="h-4 w-4 inline mr-1" />
                Rank * ({ranks.length} available)
              </label>
              <select
                name="rank_id"
                value={formData.rank_id}
                onChange={handleInputChange}
                required
                disabled={loading || 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 Rank</option>
                {ranks.map(rank => (
                  <option key={rank.id} value={rank.id}>{rank.name}</option>
                ))}
              </select>
              {ranks.length === 0 && !dataLoading && (
                <p className="text-red-500 text-xs mt-1">No ranks available</p>
              )}
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex space-x-3 mt-6 pt-4 border-t border-gray-200">
            <button
              type="button"
              onClick={handleClose}
              disabled={loading}
              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 disabled:opacity-50"
            >
              <X className="h-5 w-5" />
              <span>Cancel</span>
            </button>
            
            <button
              type="submit"
              disabled={loading || dataLoading}
              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 disabled:opacity-50"
            >
              {loading ? (
                <>
                  <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                  <span>Creating...</span>
                </>
              ) : (
                <>
                  <Save className="h-5 w-5" />
                  <span>Create User</span>
                </>
              )}
            </button>
          </div>
        </form>

        {/* 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>
    </div>
  );
};

export default AddUserDialog;
