import React, { useState, useEffect } from 'react';
import { X, Save, Building } from 'lucide-react';
import { useApp } from '../../context/AppContext';
import { departmentsApi, organizationsApi } from '../../services/api';
import { useAuth } from '../../context/AuthContext';

interface AddDepartmentDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
  unitContext?: {
    unitName: string;
    unitId: number;
    parentDepartmentId?: number;
    parentDepartmentName?: string;
  } | null;
}

const AddDepartmentDialog: React.FC<AddDepartmentDialogProps> = ({
  isOpen,
  onClose,
  onSuccess,
  unitContext
}) => {
  const { departments } = useApp();
  const { user, isSuperAdmin } = useAuth();
  const [formData, setFormData] = useState({
    name: '',
    parent_id: '',
    description: ''
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [organizations, setOrganizations] = useState<Array<{ id: number; name: string }>>([]);
  const [selectedOrgId, setSelectedOrgId] = useState<number | null>(null);
  const [availableParents, setAvailableParents] = useState<typeof departments>(departments);

  useEffect(() => {
    if (isOpen) {
      setFormData({
        name: '',
        parent_id: unitContext?.parentDepartmentId?.toString() || '',
        description: ''
      });
      setError(null);
      setSuccess(false);
      if (isSuperAdmin()) {
        loadOrganizations();
        setSelectedOrgId(null);
      } else {
        setSelectedOrgId(user?.organization_id ?? null);
        setAvailableParents(departments);
      }
    }
  }, [isOpen, unitContext]);

  const loadOrganizations = async () => {
    try {
      const resp = await organizationsApi.getOrganizations({ limit: 100 });
      if (resp.status === 'success' && resp.data) {
        setOrganizations(resp.data.organizations);
      }
    } catch {}
  };

  useEffect(() => {
    const fetchParents = async () => {
      if (isSuperAdmin() && selectedOrgId) {
        try {
          const resp = await departmentsApi.getDepartments({ limit: 1000, include_inactive: false, organization_id: selectedOrgId });
          if (resp.status === 'success' && resp.data) {
            setAvailableParents(resp.data.departments);
          } else {
            setAvailableParents(departments);
          }
        } catch {
          setAvailableParents(departments);
        }
      } else {
        setAvailableParents(departments);
      }
    };
    fetchParents();
  }, [selectedOrgId, isOpen]);


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

  // No unit linkage for departments

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.name.trim()) {
      setError('Department name is required');
      return;
    }
    if (isSuperAdmin() && !selectedOrgId) {
      setError('Organization is required');
      return;
    }
    
    // If parent department is selected, validate it exists
    let parentDepartment = null;
    if (formData.parent_id) {
      parentDepartment = availableParents.find(dept => dept.id === Number(formData.parent_id));
      if (!parentDepartment) {
        setError('Parent department not found');
        return;
      }
    }

    // No unit validation

    setLoading(true);
    setError(null);

    try {
      const departmentData = {
        name: formData.name.trim(),
        order_id: 1, // Default order_id, can be made dynamic later
        description: formData.description.trim() || undefined,
        parent_id: formData.parent_id ? Number(formData.parent_id) : null,
        organization_id: (selectedOrgId ?? user?.organization_id ?? 1)
      };

      const response = await departmentsApi.createDepartment(departmentData);

      if (response.status === 'success') {
        setSuccess(true);
        onSuccess?.();
        // Close dialog after showing success message for 1.5 seconds
        setTimeout(() => {
          onClose();
        }, 1500);
      } else {
        setError(response.message || 'Failed to create department');
      }
    } catch (error) {
      console.error('Failed to create department:', error);
      setError(error instanceof Error ? error.message : 'Failed to create department');
    } 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">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200">
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center">
              <Building className="h-5 w-5 text-green-600" />
            </div>
            <h2 className="text-lg font-semibold text-gray-900">
              {unitContext?.parentDepartmentName ? 'Add New Sub-Department' : 'Add New Department'}
            </h2>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="h-5 w-5 text-gray-500" />
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-4 space-y-4">
          {error && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-3">
              <p className="text-red-600 text-sm">{error}</p>
            </div>
          )}

          {success && (
            <div className="bg-green-50 border border-green-200 rounded-lg p-3">
              <div className="flex items-center space-x-2">
                <div className="w-5 h-5 bg-green-100 rounded-full flex items-center justify-center">
                  <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-600 text-sm font-medium">Department created successfully!</p>
              </div>
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Department/Group Name *
            </label>
            <input
              type="text"
              name="name"
              value={formData.name}
              onChange={handleInputChange}
              required
              disabled={success}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
              placeholder="Enter department name"
            />
          </div>

          <div>
            {isSuperAdmin() && (
              <>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Organization *
                </label>
                <select
                  value={selectedOrgId ?? ''}
                  onChange={(e) => setSelectedOrgId(e.target.value ? Number(e.target.value) : null)}
                  disabled={success}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
                >
                  <option value="">Select organization</option>
                  {organizations.map(org => (
                    <option key={org.id} value={org.id}>{org.name}</option>
                  ))}
                </select>
              </>
            )}
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Parent Department/Group (Optional)
            </label>
            <select
              name="parent_id"
              value={formData.parent_id}
              onChange={handleInputChange}
              disabled={success}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
            >
              <option value="">No parent department (create root department)</option>
              {availableParents
                .filter(dept => !dept.parent_id) // Only show root departments as parents
                .sort((a, b) => a.name.localeCompare(b.name))
                .map(dept => (
                  <option key={dept.id} value={dept.id}>
                    {dept.name}
                  </option>
                ))}
            </select>
            <p className="text-xs text-gray-500 mt-1">
              Select a parent department/group to create a sub-department/group, or leave empty to create a root department/group.
            </p>
          </div>

          

          {/* Parent department display when creating sub-department */}
          {formData.parent_id && unitContext?.parentDepartmentName && (
            <div className="bg-green-50 border border-green-200 rounded-lg p-3">
              <p className="text-sm text-green-800">
                <span className="font-medium">Parent Department:</span> {unitContext.parentDepartmentName}
              </p>
              
              <p className="text-xs text-green-600 mt-1">
                This sub-department will be created under the selected parent department.
              </p>
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Description
            </label>
            <textarea
              name="description"
              value={formData.description}
              onChange={handleInputChange}
              rows={3}
              disabled={success}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
              placeholder="Enter department/group description (optional)"
            />
          </div>

          {/* Actions */}
          <div className="flex items-center justify-end space-x-3 pt-4 border-t border-gray-200">
            <button
              type="button"
              onClick={onClose}
              disabled={success}
              className="px-4 py-2 text-gray-600 hover:text-gray-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {success ? 'Closing...' : 'Cancel'}
            </button>
            <button
              type="submit"
              disabled={loading || success}
              className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center space-x-2"
            >
              {loading ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                  <span>Saving...</span>
                </>
              ) : success ? (
                <>
                  <div className="w-4 h-4 bg-green-100 rounded-full flex items-center justify-center">
                    <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>
                  <span>Saved!</span>
                </>
              ) : (
                <>
                  <Save className="h-4 w-4" />
                  <span>Save Department/Group</span>
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default AddDepartmentDialog;
