// Collection picker autocomplete component

import { useMemo } from 'react'
import useCollections from '@/hooks/useCollections'
import Autocomplete from './Autocomplete'

interface CollectionOption {
  name: string
  displayName: string
}

interface CollectionAutocompleteProps {
  workspaceId?: string
  value: string
  onChange: (value: string) => void
  placeholder?: string
  label?: string
  disabled?: boolean
  allowWildcard?: boolean
  includeSystem?: boolean
}

export function CollectionAutocomplete({
  workspaceId,
  value,
  onChange,
  placeholder = 'Select collection...',
  label,
  disabled = false,
  allowWildcard = true,
  includeSystem = false,
}: CollectionAutocompleteProps) {
  const { collections, isLoading } = useCollections({
    workspaceId,
    includeSystem,
  })

  const options = useMemo(() => {
    const opts: CollectionOption[] = []

    // Add wildcard option if allowed
    if (allowWildcard) {
      opts.push({ name: '*', displayName: '* (All collections)' })
    }

    // Add collections
    for (const col of collections) {
      opts.push({ name: col.name, displayName: col.name })
    }

    return opts
  }, [collections, allowWildcard])

  return (
    <Autocomplete<CollectionOption>
      value={value}
      onChange={onChange}
      options={options}
      getDisplayValue={(item) => item.displayName}
      getValue={(item) => item.name}
      placeholder={placeholder}
      label={label}
      disabled={disabled || !workspaceId}
      loading={isLoading}
      allowCustomValue={true}
    />
  )
}

export default CollectionAutocomplete
