import { useState, useEffect } from 'react'
import { useThemeName } from '@junwon/aesthetics'
import { usePageGenerator } from '../hooks/usePageGenerator'
import { GenerativePageInHtml } from './GenerativePageInHtml'
// import { GenerativePageInReact } from './GenerativePageInReact'

interface GenerativePageProps {
  pageSpec: string
  codeToRenderDuringLoading?: string
  outputFormat?: 'html' | 'react'
}

export function GenerativePage({
  pageSpec,
  codeToRenderDuringLoading,
  outputFormat = 'html',
}: GenerativePageProps) {
  if (codeToRenderDuringLoading && !outputFormat) {
    throw new Error('outputFormat must be provided when codeToRenderDuringLoading is provided.')
  }

  const themeName = useThemeName()
  const darkModeText = themeName?.includes('dark') ? 'dark mode: true' : ''

  const { streamedBuffer } = usePageGenerator(
    `${pageSpec}\n${darkModeText}`,
    codeToRenderDuringLoading,
    outputFormat
  )
  const [renderedCode, setRenderedCode] = useState('')
  const [renderedCodeLength, setRenderedCodeLength] = useState(0)

  useEffect(() => {
    if (!streamedBuffer) return
    if (renderedCodeLength >= streamedBuffer.length) return

    const chunkSize = 10
    const delay = 10

    const processNextChunk = () => {
      const chunk = streamedBuffer.slice(renderedCodeLength, renderedCodeLength + chunkSize)
      if (chunk) {
        setRenderedCode((prev) => prev + chunk)
        setRenderedCodeLength((prev) => prev + chunk.length)
      }
    }

    const timeoutId = setTimeout(processNextChunk, delay)
    return () => clearTimeout(timeoutId)
  }, [streamedBuffer, renderedCodeLength])

  if (outputFormat === 'html') {
    return <GenerativePageInHtml renderedCode={renderedCode} />
  }

  return <GenerativePageInHtml renderedCode={renderedCode} />
  // return <GenerativePageInReact renderedCode={renderedCode} />
}
