import { connectHighlight } from "react-instantsearch-dom"
import { IHit } from '../../types'
import * as classNames from "classnames"
import includes from 'lodash/includes'
import React from "react"
import Text, { Element, Size } from "../Text"
import * as styles from './styles.module.scss'

interface IProps {
  className: string
  highlight: any
  attribute: string
  hit: IHit
}

const Snippet = ({ className, highlight, attribute, hit }: IProps) => {
  const parsedHit = highlight({
    highlightProperty: "_snippetResult",
    attribute,
    hit,
  })

  const includesLink = includes(hit.descrizioneAlgolia, "http")

  return (
    <Text
      element={Element.P}
      size={Size.P2}
      className={classNames({
        [className]: !!className,
        [styles.wordBreak]: includesLink,
      })}
    >
      {parsedHit.map((part, index) =>
        part.isHighlighted ? (
          <mark className={styles.mark} key={index}>{part.value}</mark>
        ) : (
          <span key={index}>{part.value}</span>
        )
      )}
    </Text>
  )
}

const CustomSnippet = connectHighlight(Snippet)

export default CustomSnippet
