import React, { useState, useEffect } from 'react';
import { X, Plus, Building2, Users, FileText } from 'lucide-react';
import { designationsApi, departmentsApi } from '../../services/api';
import { Designation, Department } from '../../types';

interface CreateDesignationModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  defaultDepartmentId?: number;
  defaultDepartmentName?: string;
}

const CreateDesignationModal: React.FC<CreateDesignationModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
  defaultDepartmentId,
  defaultDepartmentName
}) => {
  const [formData, setFormData] = useState({
    name: '',
    department_id: defaultDepartmentId || '',
    parent_id: '',
    description: ''
  });
  
  const [departments, setDepartments] = useState<Department[]>([]);
  const [parentDesignations, setParentDesignations] = useState<Designation[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  // Fetch departments and parent designations
  useEffect(() => {
    if (isOpen) {
      fetchDepartments();
      if (formData.department_id) {
        fetchParentDesignations(Number(formData.department_id));
      }
    }
  }, [isOpen, formData.department_id]);

  // Reset form when modal opens
  useEffect(() => {
    if (isOpen) {
      setFormData({
        name: '',
        department_id: defaultDepartmentId || '',
        parent_id: '',
        description: ''
      });
      setError(null);
      setSuccess(false);
    }
  }, [isOpen, defaultDepartmentId]);

  const fetchDepartments = async () => {
    try {
      const response = await departmentsApi.getDepartments();
      if (response.status === 'success' && response.data) {
        setDepartments(response.data.departments);
      }
    } catch (error) {
      console.error('Failed to fetch departments:', error);
    }
  };

  const fetchParentDesignations = async (departmentId: number) => {
    try {
      const response = await designationsApi.getDesignations({ 
        department_id: departmentId
        // Fetch ALL designations for the department, not just parent_id: null
      });
      if (response.status === 'success' && response.data) {
        setParentDesignations(response.data.designations);
      }
    } catch (error) {
      console.error('Failed to fetch parent designations:', error);
    }
  };

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

    // If department changes, fetch parent designations
    if (name === 'department_id') {
      setFormData(prev => ({
        ...prev,
        department_id: value,
        parent_id: '' // Reset parent designation
      }));
      if (value) {
        fetchParentDesignations(Number(value));
      } else {
        setParentDesignations([]);
      }
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.name.trim()) {
      setError('Designation name is required');
      return;
    }

    if (!formData.department_id) {
      setError('Department is required');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const response = await designationsApi.createDesignation({
        name: formData.name.trim(),
        department_id: Number(formData.department_id),
        parent_id: formData.parent_id ? Number(formData.parent_id) : null,
        description: formData.description.trim() || undefined
      });

      if (response.status === 'success') {
        setSuccess(true);
        onSuccess(); // Trigger refresh
        setTimeout(() => {
          onClose();
        }, 1500);
      } else {
        setError(response.message || 'Failed to create designation');
      }
    } catch (error) {
      console.error('Failed to create designation:', error);
      setError(error instanceof Error ? error.message : 'Failed to create designation');
    } finally {
      setLoading(false);
    }
  };

  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-100 rounded-lg flex items-center justify-center">
              <Plus className="h-5 w-5 text-blue-600" />
            </div>
            <div>
              <h2 className="text-xl font-semibold text-gray-900">Create New Designation</h2>
              <p className="text-sm text-gray-500">Add a new designation to the organizational structure</p>
            </div>
          </div>
          <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 */}
        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* Success Message */}
          {success && (
            <div className="bg-green-50 border border-green-200 rounded-lg p-4">
              <div className="flex items-center">
                <div className="w-5 h-5 bg-green-100 rounded-full flex items-center justify-center mr-3">
                  <svg className="w-3 h-3 text-green-600" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                  </svg>
                </div>
                <p className="text-green-800 font-medium">Designation created successfully!</p>
              </div>
            </div>
          )}

          {/* Error Message */}
          {error && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4">
              <div className="flex items-center">
                <div className="w-5 h-5 bg-red-100 rounded-full flex items-center justify-center mr-3">
                  <svg className="w-3 h-3 text-red-600" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                  </svg>
                </div>
                <p className="text-red-800 font-medium">{error}</p>
              </div>
            </div>
          )}

          {/* Designation Name */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <FileText className="h-4 w-4 inline mr-2" />
              Designation Name *
            </label>
            <input
              type="text"
              name="name"
              value={formData.name}
              onChange={handleInputChange}
              placeholder="e.g., Commander, Operations Officer, Senior NCO"
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
              required
            />
          </div>

          {/* Department */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <Building2 className="h-4 w-4 inline mr-2" />
              Department *
            </label>
            <select
              name="department_id"
              value={formData.department_id}
              onChange={handleInputChange}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
              required
            >
              <option value="">Select Department/Group</option>
              {departments.map(dept => (
                <option key={dept.id} value={dept.id}>
                  {dept.name}
                </option>
              ))}
            </select>
            {defaultDepartmentName && (
              <p className="text-sm text-gray-500 mt-1">
                Default: {defaultDepartmentName}
              </p>
            )}
          </div>

          {/* Parent Designation */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <Users className="h-4 w-4 inline mr-2" />
              Parent Designation/Position (Optional)
            </label>
            <select
              name="parent_id"
              value={formData.parent_id}
              onChange={handleInputChange}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
              disabled={!formData.department_id}
            >
              <option value="">No Parent (Top Level)</option>
              {parentDesignations.map(designation => (
                <option key={designation.id} value={designation.id}>
                  {designation.name}
                </option>
              ))}
            </select>
            <p className="text-sm text-gray-500 mt-1">
              Select a parent designation/position to create a hierarchical structure
            </p>
          </div>

          {/* Description */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Description (Optional)
            </label>
            <textarea
              name="description"
              value={formData.description}
              onChange={handleInputChange}
              placeholder="Brief description of the designation's responsibilities..."
              rows={3}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors resize-none"
            />
          </div>

          {/* Actions */}
          <div className="flex space-x-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-4 py-3 text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg font-medium transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading || success}
              className="flex-1 px-4 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white rounded-lg font-medium transition-colors flex items-center justify-center"
            >
              {loading ? (
                <>
                  <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  Creating...
                </>
              ) : success ? (
                'Created!'
              ) : (
                'Create Designation/Position'
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default CreateDesignationModal;
