import React, { useState, useEffect } from 'react';
import { Combobox, ComboboxInput, ComboboxOption, ComboboxOptions } from '@headlessui/react';
import type { Tag } from '@/utils/types';

interface TagSearchProps {
  all_tags: Tag[],
  selectedTagIds: number[];
  onToggle: (tag: number) => void;
}

export const TagSearch: React.FC<TagSearchProps> = ({ all_tags, selectedTagIds, onToggle }) => {

  const [tagQuery, setTagQuery] = useState('')

  const tag_options = all_tags;

  const filteredTags =
    (tagQuery === '' || tagQuery.length < 2) ?
    [] :
    tag_options.filter((tag) => (
      tag.tag.toLowerCase().startsWith(tagQuery.toLowerCase())
    ));


  return (
    <Combobox
      value={selectedTagIds}
      /*virtual={{ options: filteredTags }}*/
      onChange={(tag_id) => {
        if (typeof tag_id === 'number') {
          onToggle(tag_id);
        }
      }}
      onClose={() => setTagQuery('')}
    >
      <ComboboxInput
        aria-label="Assignee"
        /*displayValue={(tag: Tag) => tag?.tag}*/
        className='border data-[hover]:shadow data-[focus]:bg-blue-100 w-full'
        onChange={(event) => setTagQuery(event.target.value)}
      />
      <ComboboxOptions anchor="bottom" className="w-52 empty:hidden border-2">
        {filteredTags.map((tag) => (
          <ComboboxOption key={tag.index} value={tag.index} className="group flex gap-2 bg-white data-[focus]:bg-blue-100">
            {tag.tag}
          </ComboboxOption>
        ))}
      </ComboboxOptions>
    </Combobox>
  )
};