import { Fragment, useState } from 'react';
import { Listbox, Transition } from '@headlessui/react';
import { CheckIcon, ChevronUpDownIcon } from '@heroicons/react/24/outline';

interface Option {
  value: string;
  label: string;
}

interface MultiSelectProps {
  options: Option[];
  selected: string[];
  onChange: (selected: string[]) => void;
  placeholder?: string;
  className?: string;
}

export function MultiSelect({ options, selected, onChange, placeholder = 'Select...', className = '' }: MultiSelectProps) {
  const [isOpen, setIsOpen] = useState(false);

  const handleToggle = (value: string) => {
    if (selected.includes(value)) {
      onChange(selected.filter(v => v !== value));
    } else {
      onChange([...selected, value]);
    }
  };

  const selectedLabels = selected.map(value => 
    options.find(opt => opt.value === value)?.label || value
  ).join(', ');

  return (
    <div className={`relative ${className}`}>
      <Listbox value={selected} onChange={() => {}} multiple>
        <div className="relative">
          <Listbox.Button 
            onClick={() => setIsOpen(!isOpen)}
            className="relative w-full cursor-default rounded-md bg-background border border-border py-1 pl-2 pr-8 text-left text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
          >
            <span className={`block truncate ${selected.length === 0 ? 'text-text-secondary' : ''}`}>
              {selected.length > 0 ? selectedLabels : placeholder}
            </span>
            <span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
              <ChevronUpDownIcon className="h-4 w-4 text-text-secondary" aria-hidden="true" />
            </span>
          </Listbox.Button>
          <Transition
            show={isOpen}
            as={Fragment}
            leave="transition ease-in duration-100"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
          >
            <Listbox.Options 
              static
              className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-background border border-border py-1 text-sm shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"
            >
              {options.map((option) => (
                <Listbox.Option
                  key={option.value}
                  value={option.value}
                  disabled={false}
                  className={({ active }) =>
                    `relative cursor-pointer select-none py-2 pl-10 pr-4 ${
                      active ? 'bg-surface-secondary text-text-primary' : 'text-text-primary'
                    }`
                  }
                  onClick={(e) => {
                    e.preventDefault();
                    handleToggle(option.value);
                  }}
                >
                  <>
                    <span className={`block truncate ${selected.includes(option.value) ? 'font-medium' : 'font-normal'}`}>
                      {option.label}
                    </span>
                    {selected.includes(option.value) ? (
                      <span className="absolute inset-y-0 left-0 flex items-center pl-3 text-primary-500">
                        <CheckIcon className="h-4 w-4" aria-hidden="true" />
                      </span>
                    ) : null}
                  </>
                </Listbox.Option>
              ))}
            </Listbox.Options>
          </Transition>
        </div>
      </Listbox>
    </div>
  );
}