import type { ShikiResult, SyntaxHighlighterProps, ThemedToken } from '../types/shiki'
import { useEffect, useState } from 'react'
import { createHighlighter } from '../syntax'

export function useSyntaxHighlighter({ text, lang, langName, theme, themeName }: SyntaxHighlighterProps) {
  const [tokens, setTokens] = useState<ThemedToken[][]>([])
  const [error, setError] = useState<string>()
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    let mounted = true
    setIsLoading(true)

    async function highlight() {
      if (!text) {
        setIsLoading(false)
        setTokens([])
        return
      }

      try {
        const highlighter = await createHighlighter({
          langs: [lang],
          themes: [theme],
        })

        const result = highlighter.codeToTokens(text, {
          lang: langName,
          theme: themeName,
        }) as ShikiResult

        if (mounted && result.tokens) {
          setTokens(result.tokens)
          setError(undefined)
        }
      }
      catch (err) {
        console.error('Highlighting error:', err)
        if (mounted) {
          setError(err instanceof Error ? err.message : 'Syntax highlighting failed')
          setTokens([])
        }
      }
      finally {
        if (mounted) {
          setIsLoading(false)
        }
      }
    }

    highlight()
    return () => {
      mounted = false
    }
  }, [text, lang, langName, theme, themeName])

  return { tokens, error, isLoading }
}
