import { FC } from 'preact/compat'
import { useCallback, useMemo } from 'preact/hooks'
import { className } from '../../../lib/css'
import Icon from '../layout/icon'

export const mapCategoryToClass = (category) =>
  `suggestions__item--${String(category)
    .toLowerCase()
    .replace(/[^a-z0-9_\\-]/, '')}`

type SuggestionsItemProps = {
  id: string | number | undefined
  className?: string
  onClick: (_args: {
    id: string | number | undefined
    question?: string | undefined
  }) => void
  categories?: (string | number)[] | undefined
  hasIcon?: boolean
  question?: string | undefined
}

const SuggestionsItem: FC<SuggestionsItemProps> = ({
  id,
  categories = [],
  question,
  onClick,
  hasIcon,
}) => {
  const mappedClassNames = useMemo(() => {
    return ['suggestions__item', ...categories.map(mapCategoryToClass)]
  }, [categories])

  const handleClick = useCallback(() => {
    if (onClick) {
      onClick({ id, question })
    }
  }, [id, question, onClick])
  return (
    <li className={className(mappedClassNames)}>
      <button
        type="button"
        onClick={handleClick}
        className={className('button', 'button--primary')}
      >
        {hasIcon && <Icon name="chevronRight" size="8" alt="" />}
        {question}
      </button>
    </li>
  )
}

export default SuggestionsItem
