import type { LanguageInput, ThemeInput } from 'shiki'
import React from 'react'
import { Text, View } from 'react-native'
import { useSyntaxHighlighter } from '../../hooks/useSyntaxHighlighter'
import typescript from '../../vendor/shiki/langs/typescript'
import githubDark from '../../vendor/shiki/themes/github-dark'

interface SyntaxHighlighterProps {
  text: string
  lang?: LanguageInput
  langName?: string
  theme?: ThemeInput
  themeName?: string
  fontSize?: number
}

function SyntaxHighlighter({
  text,
  lang = typescript,
  langName = 'typescript',
  theme = githubDark,
  themeName = 'github-dark',
  fontSize,
}: SyntaxHighlighterProps) {
  const { tokens, error, isLoading } = useSyntaxHighlighter({
    text,
    lang,
    langName,
    theme,
    themeName,
  })

  if (error) {
    return (
      <Text style={{ color: '#ff6b6b', fontFamily: 'monospace', fontSize }}>
        Error:
        {' '}
        {error}
      </Text>
    )
  }

  if (isLoading) {
    return <Text style={{ color: '#f8f8f2', fontFamily: 'monospace', fontSize }}>Loading...</Text>
  }

  return (
    <View>
      {tokens.map((line, lineIndex) => (
        <View key={`line-${lineIndex}`} style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
          {line.map((token, tokenIndex) => (
            <Text
              key={`${lineIndex}-${tokenIndex}`}
              style={{
                color: token.color || '#FFFFFF',
                fontFamily: 'monospace',
                fontSize,
                fontStyle: token.fontStyle as unknown as 'normal' | 'italic',
              }}
            >
              {token.content.replace(/ /g, '\u00A0')}
            </Text>
          ))}
          <Text style={{ color: '#FFFFFF', fontFamily: 'monospace', fontSize }}>{'\n'}</Text>
        </View>
      ))}
    </View>
  )
}

export default SyntaxHighlighter
