import React from 'react'

import { QueryMatch } from '~/src/store/selectors/selectFilteredEventList'

import { useTextMatchGroups } from './hooks'
import {
  Breadcrumbs,
  Key,
  KeyPathFragment,
  MatchPreview,
  QueryMatchContainer,
  TextLikeValue,
  NonTextValue,
  HighlightedText,
  ColonSeparator
} from './style'


export type QueryMatchPreviewProps = {
  children: QueryMatch
}

export const QueryMatchPreview = ({
  children: { keyPath, value, matchingKeyRange, matchingValueRange }
}: QueryMatchPreviewProps) => {
  const keyMatch = useTextMatchGroups(keyPath.at(-1).value, matchingKeyRange)
  const valueMatch = useTextMatchGroups(value, matchingValueRange)

  return (
    <QueryMatchContainer>
      <Breadcrumbs>
        {keyPath.map((fragment, i) => (
          <KeyPathFragment key={i} fragmentType={fragment.type}>
            {fragment.value}
          </KeyPathFragment>
        ))}
      </Breadcrumbs>
      <MatchPreview>
        <Key type={keyPath.at(-1).type}>
          {keyMatch.head}
          {keyMatch.match && <HighlightedText>{keyMatch.match}</HighlightedText>}
          {keyMatch.tail}
        </Key>
        <ColonSeparator />
        {['string', 'number', 'boolean'].includes(typeof value) ? (
          <TextLikeValue formatAs={typeof value}>
            <span>{valueMatch.head}</span>
            {valueMatch.match && <HighlightedText>{valueMatch.match}</HighlightedText>}
            <span>
              {/* // the tail is rendered in rtl mode for ellipsis to be on the left,
              so we need the &lrm to mirror the punctuation and spaces properly */}
              &lrm;{valueMatch.tail}
            </span>
          </TextLikeValue>
        ) : (
          <NonTextValue rawValue={value} />
        )}
      </MatchPreview>
    </QueryMatchContainer>
  )
}
