import React, { useState, useEffect } from 'react';
import { X, Save, Building2 } from 'lucide-react';
import { organizationalApi } from '../../services/api';
import { Unit } from '../../types';

interface UnitDialogProps {
  unit: Unit | null;
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  mode: 'add' | 'edit' | 'view';
}

const UnitDialog: React.FC<UnitDialogProps> = ({
  unit,
  isOpen,
  onClose,
  onSuccess,
  mode
}) => {
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    parent_id: null as number | null,
    order_id: 1,
    is_active: true
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [parentUnits, setParentUnits] = useState<Unit[]>([]);

  // Load parent units for dropdown
  useEffect(() => {
    if (isOpen && mode !== 'view') {
      loadParentUnits();
    }
  }, [isOpen, mode]);

  // Load unit data when editing
  useEffect(() => {
    if (unit && mode === 'edit') {
      setFormData({
        name: unit.name || '',
        description: unit.description || '',
        parent_id: unit.parent_id || null,
        order_id: unit.order_id || 1,
        is_active: unit.is_active !== false
      });
    } else if (mode === 'add') {
      setFormData({
        name: '',
        description: '',
        parent_id: null,
        order_id: 1,
        is_active: true
      });
    }
  }, [unit, mode]);

  const loadParentUnits = async () => {
    try {
      console.log('🔍 Loading parent units...');
      const response = await organizationalApi.getUnits({ 
        limit: 1000,
        include_inactive: false 
      });
      console.log('🔍 Parent units response:', response);
      
      if (response.status === 'success' && response.data) {
        // Filter out current unit if editing to prevent self-reference
        const filteredUnits = unit 
          ? response.data.units.filter(u => u.id !== unit.id)
          : response.data.units;
        console.log('🔍 Filtered parent units:', filteredUnits);
        // Convert API units to local Unit type
        const convertedUnits = filteredUnits.map(u => ({
          ...u,
          is_active: u.is_active === 1
        }));
        setParentUnits(convertedUnits);
      } else {
        console.error('🔍 Failed to load parent units:', response.message);
      }
    } catch (error) {
      console.error('❌ Error loading parent units:', error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (mode === 'view') return;

    setLoading(true);
    setError(null);

    try {
      // Add empty code field for backward compatibility with API
      // Convert null to undefined for parent_id
      const submitData = { 
        ...formData, 
        code: '',
        parent_id: formData.parent_id ?? undefined 
      };
      
      if (mode === 'add') {
        const response = await organizationalApi.createUnit(submitData);
        if (response.status === 'success') {
          onSuccess();
          onClose();
        } else {
          throw new Error(response.message || 'Failed to create unit');
        }
      } else if (mode === 'edit' && unit) {
        const response = await organizationalApi.updateUnit(unit.id, submitData);
        if (response.status === 'success') {
          onSuccess();
          onClose();
        } else {
          throw new Error(response.message || 'Failed to update unit');
        }
      }
    } catch (error: any) {
      console.error('Error saving unit:', error);
      setError(error.message || 'An error occurred while saving the unit');
    } finally {
      setLoading(false);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : 
              name === 'parent_id' ? (value === '' ? null : parseInt(value)) :
              name === 'order_id' ? parseInt(value) || 1 : value
    }));
  };

  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-lg p-6 w-full max-w-md mx-4 max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900 flex items-center">
            <Building2 className="h-5 w-5 mr-2" />
            {mode === 'add' ? 'Add New Unit' : 
             mode === 'edit' ? 'Edit Unit' : 
             'View Unit'}
          </h3>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {error && (
          <div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Unit Name *
            </label>
            <input
              type="text"
              name="name"
              value={formData.name}
              onChange={handleInputChange}
              disabled={mode === 'view'}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
              required
            />
          </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}
              disabled={mode === 'view'}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
              min="1"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Parent Unit
            </label>
            <select
              name="parent_id"
              value={formData.parent_id || ''}
              onChange={handleInputChange}
              disabled={mode === 'view'}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
            >
              <option value="">No Parent Unit</option>
              {parentUnits.map(parent => (
                <option key={parent.id} value={parent.id}>
                  {parent.name}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Description
            </label>
            <textarea
              name="description"
              value={formData.description}
              onChange={handleInputChange}
              disabled={mode === 'view'}
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
            />
          </div>

          {mode !== 'view' && (
            <div className="flex items-center">
              <input
                type="checkbox"
                name="is_active"
                checked={formData.is_active}
                onChange={handleInputChange}
                className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
              />
              <label className="ml-2 block text-sm text-gray-700">
                Active
              </label>
            </div>
          )}

          <div className="flex space-x-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
            >
              {mode === 'view' ? 'Close' : 'Cancel'}
            </button>
            {mode !== 'view' && (
              <button
                type="submit"
                disabled={loading}
                className="flex-1 flex items-center justify-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {loading ? (
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                ) : (
                  <>
                    <Save className="h-4 w-4 mr-2" />
                    {mode === 'add' ? 'Create Unit' : 'Update Unit'}
                  </>
                )}
              </button>
            )}
          </div>
        </form>
      </div>
    </div>
  );
};

export default UnitDialog;
