import React, { useEffect } from 'react';
import { ChevronDown, RefreshCw } from 'lucide-react';
import { Department } from '../../types';
import { useApp } from '../../context/AppContext';

interface DepartmentDropdownProps {
  value: number | string;
  onChange: (value: number | string) => void;
  placeholder?: string;
  className?: string;
  disabled?: boolean;
  required?: boolean;
  unitId?: number | string;
}

const DepartmentDropdown: React.FC<DepartmentDropdownProps> = ({
  value,
  onChange,
  placeholder = 'Select Department/Group',
  className = '',
  disabled = false,
  required = false,
  unitId
}) => {
  const { departments, departmentsLoading, departmentsError, fetchDepartments } = useApp();

  // Filter departments based on unitId and sort by ID
  const filteredDepartments = departments.slice().sort((a, b) => a.id - b.id);

  // Reset department selection when unit changes
  useEffect(() => {
    if (unitId && unitId !== 'all' && departments.length > 0) {
      const currentDepartment = departments.find(dept => dept.id === Number(value));
      // No unit-specific filtering anymore
    }
  }, [unitId, value, departments, onChange]);

  const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const selectedValue = e.target.value;
    if (selectedValue === '' || selectedValue === 'all') {
      onChange('all');
    } else {
      onChange(parseInt(selectedValue));
    }
  };

  const getDisplayValue = (dept: Department) => {
    return dept.name;
  };

  if (departmentsLoading) {
    return (
      <div className={`relative ${className}`}>
        <div className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-100 text-gray-500 cursor-not-allowed flex items-center justify-between">
          <span>Loading departments/groups...</span>
          <RefreshCw className="h-4 w-4 animate-spin" />
        </div>
      </div>
    );
  }

  if (departmentsError) {
    return (
      <div className={`relative ${className}`}>
        <div className="w-full px-3 py-2 border border-red-300 rounded-lg bg-red-50 text-red-500 cursor-not-allowed flex items-center justify-between">
          <span>Error loading departments/groups</span>
          <button
            onClick={() => fetchDepartments()}
            disabled={departmentsLoading}
            className="ml-2 p-1 hover:bg-red-100 rounded transition-colors"
            title="Retry loading departments/groups"
          >
            <RefreshCw className={`h-4 w-4 ${departmentsLoading ? 'animate-spin' : ''}`} />
          </button>
        </div>
        <p className="text-xs text-red-500 mt-1">{departmentsError}</p>
      </div>
    );
  }

  return (
    <div className={`relative ${className}`}>
      <select
        value={value}
        onChange={handleChange}
        disabled={disabled}
        required={required}
        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 disabled:cursor-not-allowed appearance-none pr-8"
      >
        <option value="all">{placeholder}</option>
        {filteredDepartments.map((dept) => (
          <option key={dept.id} value={dept.id}>
            {getDisplayValue(dept)}
          </option>
        ))}
      </select>
      <ChevronDown className="absolute right-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
    </div>
  );
};

export default DepartmentDropdown;
