import React from 'react';
import { useTranslation } from 'react-i18next';
import { 
  Users, 
  Search,
  Check,
  X,
  AlertCircle
} from 'lucide-react';
import { Resource } from '../../types';
import FormInput from '../ui/FormInput';
import Badge from '../ui/Badge';

interface ResourceSelectorProps {
  resources: Resource[];
  selectedIds: string[];
  allSelected: boolean;
  onChange: (ids: string[], all: boolean) => void;
}

export const ResourceSelector: React.FC<ResourceSelectorProps> = ({
  resources,
  selectedIds,
  allSelected,
  onChange
}) => {
  const { t } = useTranslation();
  const [search, setSearch] = React.useState('');

  const filteredResources = resources.filter(r => 
    r.name.toLowerCase().includes(search.toLowerCase())
  );

  const handleToggle = (id: string) => {
    if (allSelected) {
      // If switching from All to Specific, start with just this one selected? 
      // Or keep all others selected?
      // Better UX: "All" is a special mode. If you uncheck one, you enter "Specific" mode with all-minus-one selected.
      // But we don't have all IDs readily available without mapping.
      // Let's assume typical toggle logic.
      
      // Actually, if "All" is true, we should probably toggle it OFF and select just this ID? 
      // Or select all EXCEPT this ID?
      // Let's simplify: Toggle "All Staff" switch separately.
      return; 
    }

    const newIds = selectedIds.includes(id)
      ? selectedIds.filter(i => i !== id)
      : [...selectedIds, id];
    
    onChange(newIds, false);
  };

  const handleAllToggle = () => {
    if (!allSelected) {
      onChange([], true);
    } else {
      onChange([], false); // Clear selection or keep? Let's clear for now.
    }
  };

  return (
    <div className="space-y-4">
      {/* Header / All Toggle */}
      <div className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-brand-100 dark:bg-brand-900/30 rounded-lg text-brand-600 dark:text-brand-400">
            <Users size={20} />
          </div>
          <div>
            <h4 className="font-medium text-gray-900 dark:text-white">All Staff Available</h4>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Automatically include current and future staff
            </p>
          </div>
        </div>
        <label className="relative inline-flex items-center cursor-pointer">
          <input 
            type="checkbox" 
            className="sr-only peer"
            checked={allSelected}
            onChange={handleAllToggle}
          />
          <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-brand-300 dark:peer-focus:ring-brand-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-brand-600"></div>
        </label>
      </div>

      {!allSelected && (
        <div className="border border-gray-200 dark:border-gray-700 rounded-xl overflow-hidden animate-in slide-in-from-top-2 duration-200">
          <div className="p-3 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search staff..."
                className="w-full pl-9 pr-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 focus:ring-2 focus:ring-brand-500 outline-none"
              />
            </div>
          </div>
          
          <div className="max-h-60 overflow-y-auto p-2 bg-white dark:bg-gray-800 space-y-1">
            {filteredResources.length === 0 ? (
              <div className="p-4 text-center text-gray-500 dark:text-gray-400 text-sm">
                No staff found matching "{search}"
              </div>
            ) : (
              filteredResources.map(resource => (
                <button
                  key={resource.id}
                  type="button"
                  onClick={() => handleToggle(resource.id)}
                  className={`w-full flex items-center justify-between p-3 rounded-lg text-left transition-colors ${
                    selectedIds.includes(resource.id)
                      ? 'bg-brand-50 dark:bg-brand-900/20 text-brand-900 dark:text-brand-100'
                      : 'hover:bg-gray-50 dark:hover:bg-gray-700/50 text-gray-700 dark:text-gray-300'
                  }`}
                >
                  <div className="flex items-center gap-3">
                    <div className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-medium ${
                      selectedIds.includes(resource.id)
                        ? 'bg-brand-200 dark:bg-brand-800 text-brand-700 dark:text-brand-300'
                        : 'bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
                    }`}>
                      {resource.name.charAt(0)}
                    </div>
                    <span>{resource.name}</span>
                  </div>
                  {selectedIds.includes(resource.id) && (
                    <Check size={18} className="text-brand-600 dark:text-brand-400" />
                  )}
                </button>
              ))
            )}
          </div>
          
          <div className="p-3 bg-gray-50 dark:bg-gray-800/50 border-t border-gray-200 dark:border-gray-700 text-xs text-gray-500 dark:text-gray-400 flex justify-between">
            <span>{selectedIds.length} staff selected</span>
            {selectedIds.length === 0 && (
              <span className="text-amber-600 dark:text-amber-400 flex items-center gap-1">
                <AlertCircle size={12} /> At least one required
              </span>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default ResourceSelector;
