import React, { useState, useEffect } from 'react';
import { X, Save, Tag } from 'lucide-react';
import { designationsApi, departmentsApi } from '../../services/api';
import { Designation, Department } from '../../types';
import { useAuth } from '../../context/AuthContext';

interface DesignationDialogProps {
  designation: Designation | null;
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  mode: 'add' | 'edit' | 'view';
}

const DesignationDialog: React.FC<DesignationDialogProps> = ({
  designation,
  isOpen,
  onClose,
  onSuccess,
  mode
}) => {
  const { isSuperAdmin, hasPermission } = useAuth();
  const [formData, setFormData] = useState({
    name: '',
    department_id: null as number | null,
    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 [departments, setDepartments] = useState<Department[]>([]);
  const [parentDesignations, setParentDesignations] = useState<Designation[]>([]);

  // Load departments and parent designations for dropdowns
  useEffect(() => {
    if (isOpen && mode !== 'view') {
      loadDepartments();
      loadParentDesignations();
    }
  }, [isOpen, mode]);

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

  const loadDepartments = async () => {
    try {
      console.log('🔍 Loading departments for designation...');
      const response = await departmentsApi.getDepartments({
        limit: 1000,
        include_inactive: false
      });
      console.log('🔍 Departments response:', response);

      if (response.status === 'success' && response.data) {
        console.log('🔍 Departments data:', response.data.departments);
        setDepartments(response.data.departments);
      } else {
        console.error('🔍 Failed to load departments:', response.message);
      }
    } catch (error) {
      console.error('❌ Error loading departments:', error);
    }
  };

  const loadParentDesignations = async () => {
    try {
      console.log('🔍 Loading parent designations...');
      const response = await designationsApi.getDesignations({
        limit: 1000,
        include_inactive: false
      });
      console.log('🔍 Parent designations response:', response);

      if (response.status === 'success' && response.data) {
        // Filter out current designation if editing to prevent self-reference
        const filteredDesignations = designation
          ? response.data.designations.filter(d => d.id !== designation.id)
          : response.data.designations;
        console.log('🔍 Filtered parent designations:', filteredDesignations);
        setParentDesignations(filteredDesignations);
      } else {
        console.error('🔍 Failed to load parent designations:', response.message);
      }
    } catch (error) {
      console.error('❌ Error loading parent designations:', error);
    }
  };

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

    setError(null);
    setLoading(true);

    // Basic validation
    if (!formData.name.trim()) {
      setError('Designation name is required.');
      setLoading(false);
      return;
    }

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

    try {
      let response;
      if (mode === 'add') {
        response = await designationsApi.createDesignation(formData);
      } else { // mode === 'edit'
        if (!designation?.id) {
          throw new Error('Designation ID is missing for update operation.');
        }
        response = await designationsApi.updateDesignation(designation.id, formData);
      }

      if (response.status === 'success') {
        onSuccess();
        onClose();
      } else {
        throw new Error(response.message || `Failed to ${mode} designation.`);
      }
    } catch (err: any) {
      console.error(`Error ${mode}ing designation:`, err);
      setError(err.message || `Failed to ${mode} designation. Please try again.`);
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  const isEditable = mode === 'add' || mode === 'edit';
  const dialogTitle = mode === 'add' ? 'Add New Designation' : mode === 'edit' ? 'Edit Designation' : 'View Designation';

  // Permission check for editing/adding
  const canEdit = isSuperAdmin() || hasPermission('designation.update');
  const canAdd = isSuperAdmin() || hasPermission('designation.create');

  if (!canEdit && mode === 'edit') {
    setError('You do not have permission to edit designations.');
  }
  if (!canAdd && mode === 'add') {
    setError('You do not have permission to add designations.');
  }

  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 shadow-xl">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900">{dialogTitle}</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="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
            <strong className="font-bold">Error!</strong>
            <span className="block sm:inline"> {error}</span>
          </div>
        )}

        <form onSubmit={handleSubmit}>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Designation Name *
              </label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                placeholder="Enter designation name"
                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"
                disabled={!isEditable || loading}
                required
              />
            </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={(e) => setFormData(prev => ({ ...prev, department_id: e.target.value ? parseInt(e.target.value) : null }))}
                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"
                disabled={!isEditable || loading}
                required
              >
                <option value="">Select Department</option>
                {departments.map(dept => (
                  <option key={dept.id} value={dept.id}>{dept.name}</option>
                ))}
              </select>
            </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={(e) => setFormData(prev => ({ ...prev, order_id: parseInt(e.target.value) || 1 }))}
                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"
                disabled={!isEditable || loading}
                min="1"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Description
              </label>
              <textarea
                name="description"
                value={formData.description}
                onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                placeholder="Enter designation description"
                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:opacity-50"
                disabled={!isEditable || loading}
              ></textarea>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Parent Designation (Optional)
              </label>
              <select
                name="parent_id"
                value={formData.parent_id || ''}
                onChange={(e) => setFormData(prev => ({ ...prev, parent_id: e.target.value ? parseInt(e.target.value) : null }))}
                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"
                disabled={!isEditable || loading}
              >
                <option value="">No Parent Designation</option>
                {parentDesignations.map(pDesignation => (
                  <option key={pDesignation.id} value={pDesignation.id}>{pDesignation.name}</option>
                ))}
              </select>
            </div>

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

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

export default DesignationDialog;
