import React, { useState, useEffect } from 'react';
import { X, Save, FolderOpen } from 'lucide-react';
import { departmentsApi, organizationalApi, organizationsApi } from '../../services/api';
import { Department, Unit } from '../../types';
import { useAuth } from '../../context/AuthContext';

interface DepartmentDialogProps {
  department: Department | null;
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  mode: 'add' | 'edit' | 'view';
}

const DepartmentDialog: React.FC<DepartmentDialogProps> = ({
  department,
  isOpen,
  onClose,
  onSuccess,
  mode
}) => {
  const { isSuperAdmin, hasPermission } = useAuth();
  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 [units, setUnits] = useState<Unit[]>([]);
  const [parentDepartments, setParentDepartments] = useState<Department[]>([]);
  const [organizations, setOrganizations] = useState<Array<{ id: number; name: string }>>([]);
  const [selectedOrgId, setSelectedOrgId] = useState<number | null>(null);
  const [myOrganizationName, setMyOrganizationName] = useState<string>('');

  // Load units and parent departments for dropdowns
  useEffect(() => {
    if (isOpen && mode !== 'view') {
      loadParentDepartments();
      if (isSuperAdmin()) {
        loadOrganizations();
        setSelectedOrgId(null);
      } else {
        setSelectedOrgId(null);
        loadMyOrganization();
      }
    }
  }, [isOpen, mode]);

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

  // Units are no longer required for departments

  const loadParentDepartments = async () => {
    try {
      console.log('🔍 Loading parent departments...');
      const response = await departmentsApi.getDepartments({
        limit: 1000,
        include_inactive: false
      });
      console.log('🔍 Parent departments response:', response);

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

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

    setError(null);
    setLoading(true);

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

    // No unit required

    try {
      let response;
      if (mode === 'add') {
        if (isSuperAdmin() && !selectedOrgId) {
          setError('Organization is required.');
          setLoading(false);
          return;
        }
        response = await departmentsApi.createDepartment({
          ...formData,
          organization_id: selectedOrgId ?? undefined
        });
      } else { // mode === 'edit'
        if (!department?.id) {
          throw new Error('Department ID is missing for update operation.');
        }
        response = await departmentsApi.updateDepartment(department.id, formData);
      }

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

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

  const loadMyOrganization = async () => {
    try {
      const resp = await organizationsApi.getMyOrganization();
      if (resp.status === 'success' && resp.data) {
        const org = (resp.data as any).organization;
        setSelectedOrgId(org?.id ?? null);
        setMyOrganizationName(org?.name ?? 'My Organization');
      }
    } catch {}
  };

  if (!isOpen) return null;

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

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

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

  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">
                Department/Group Name *
              </label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                placeholder="Enter department/group 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>

            {mode === 'add' && (
              <div>
                <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)}
                  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 || !isSuperAdmin()}
                >
                  {!isSuperAdmin() ? (
                    <option value={selectedOrgId ?? ''}>{myOrganizationName || 'My Organization'}</option>
                  ) : (
                    <>
                      <option value="">Select organization</option>
                      {organizations.map(org => (
                        <option key={org.id} value={org.id}>{org.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 department/group 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 Department/Group (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 Department/Group</option>
                {parentDepartments.map(pDept => (
                  <option key={pDept.id} value={pDept.id}>{pDept.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 Department/Group'
                ) : (
                  'Update Department/Group'
                )}
              </button>
            </div>
          )}
        </form>
      </div>
    </div>
  );
};

export default DepartmentDialog;
