import React, { useCallback, useEffect, useState } from 'react'
import classNames from 'classnames'
import { TranscriptionResultItem } from '@zocks-communications/client-sdk-js'
import { useParticipantTranscript } from '../../store'
import './TranscriptionDisplay.module.scss'

export const TranscriptionDisplay: React.FC<{
  participantId: string
  wordsInLine?: number
  hideDelay?: number
}> = ({ participantId, wordsInLine = 10, hideDelay = 3 }) => {
  const { displayTranscriptions, finalTranscripts, partialTranscript } = useParticipantTranscript(
    participantId,
    hideDelay
  )
  const [finalItems, setFinalItems] = useState<TranscriptionResultItem[]>([])
  const lastFullTranscript = finalTranscripts[finalTranscripts.length - 1]

  const mergePunctuation = useCallback((items: TranscriptionResultItem[]): TranscriptionResultItem[] => {
    const isPunctuation = (c: string) => !!c.match(/^[.,:!?]/)
    return items.reduce((prev: TranscriptionResultItem[], current, currentIndex, array) => {
      if (!isPunctuation(current.content)) {
        const nextContent = array[currentIndex + 1]?.content
        if (nextContent && isPunctuation(nextContent)) {
          prev.push({ ...current, content: current.content + nextContent })
        } else {
          prev.push(current)
        }
      }
      return prev
    }, [])
  }, [])

  useEffect(() => {
    if (lastFullTranscript) {
      setFinalItems((i) => i.concat(mergePunctuation(lastFullTranscript.items)))
    }
  }, [lastFullTranscript, mergePunctuation, wordsInLine])

  useEffect(() => {
    const timeout = setTimeout(() => setFinalItems([]), hideDelay * 1000)
    return () => clearTimeout(timeout)
  }, [lastFullTranscript, partialTranscript, hideDelay])

  if (!displayTranscriptions || (!finalItems.length && !partialTranscript)) {
    return null
  }

  const createTextItems = (items: TranscriptionResultItem[]) =>
    items.map((i, idx) => {
      return (
        <span className={classNames({ 'transcription-display__partial-result': !i.isStable })} key={idx}>
          {`${i.content} `}
        </span>
      )
    })

  const items = partialTranscript ? [...finalItems, ...mergePunctuation(partialTranscript.items)] : finalItems
  const secondLineOffset = items.length % wordsInLine || wordsInLine
  const firstLine = items.slice(-secondLineOffset - wordsInLine, -secondLineOffset)
  const secondLine = items.slice(-secondLineOffset)

  return (
    <div className='transcription-display__container'>
      {firstLine.length ? <div className='transcription-display__line'>{createTextItems(firstLine)}</div> : null}
      {secondLine.length ? <div className='transcription-display__line'>{createTextItems(secondLine)}</div> : null}
    </div>
  )
}
