import { useId, useMemo } from "react"

export function useDataList(list: string[]): {
  id: string
  element: React.ReactElement
}

export function useDataList<K extends string>(
  list: { [key in K]: string }[],
  propertyKey?: K,
): {
  id: string
  element: React.ReactElement
}

export function useDataList(list: any[], key?: string) {
  const id = useId()

  const element = useMemo(
    () => (
      <datalist id={id}>
        {key
          ? list.map(value => <option key={value[key]} value={value[key]} />)
          : list.map(value => <option key={value} value={value} />)}
      </datalist>
    ),
    [id, list, key],
  )

  return {
    id,
    element,
  }
}
