import { LinkCardProps, InfoCardProps } from '@junwon/centum'
import { Page } from '@my/ui'
import usePageOpener from 'app/utils/catalog/usePageOpener'
import { getServerAddress } from 'app/utils/getServerAddress'
import { EventSourcePolyfill as EventSource } from 'event-source-polyfill'
import React, { useEffect, useState, useCallback } from 'react'
import { useParams } from 'solito/navigation'

export const ListPage = () => {
  const params = useParams()
  const { openPageLink } = usePageOpener()
  const [title, setTitle] = useState<string>('Title')
  const [headline, setHeadline] = useState<string>('This is a cool headline')
  const [cards, setCards] = useState<InfoCardProps[]>([])
  const [linkCards, setLinkCards] = useState<LinkCardProps[]>([])
  const [loading, setLoading] = useState<boolean>(true)
  const [streamId, setStreamId] = useState<string | null>(null)

  const fetchListData = useCallback(async () => {
    if (params?.title) {
      setTitle('Loading')
      setHeadline('I am checking the catalog to see if we have this list.')
      setLoading(true)
      const serverAddress = getServerAddress()
      try {
        const url = `${serverAddress}/list/${params.title}`
        const response = await fetch(url, { method: 'POST' })
        const data = await response.json()

        if (data.action === 'render_list_data') {
          const { title, headline, cards, link_cards } = data.list_data
          setTitle(title || 'Title')
          setHeadline(headline || 'Headline')
          setCards(cards || [])
          setLinkCards(link_cards || [])
        } else if (data.action === 'inform_missing_list') {
          setStreamId(data.stream_id)
          setTitle(data.list_title)
          setHeadline(
            'You have reached a list which no one has reached yet. I am generating the content for you now. Please wait a moment.'
          )
          setLinkCards(data.link_cards || [])
        } else {
          console.warn('Unexpected Server Response:', data.action)
        }
      } catch (error) {
        console.error('Error fetching list data:', error)
      } finally {
        setLoading(false)
      }
    }
  }, [params])

  useEffect(() => {
    fetchListData()
  }, [params, fetchListData])

  useEffect(() => {
    if (streamId) {
      const serverAddress = getServerAddress()
      const eventSource = new EventSource(`${serverAddress}/stream/${streamId}`)

      eventSource.onmessage = (event) => {
        const eventData = event.data
        try {
          const data = JSON.parse(eventData)
          if (data.action === 'content_generated') {
            const list_data = data.list
            setTitle(list_data.title || 'Title')
            setHeadline(list_data.headline || 'Headline')
            setCards(list_data.cards || [])
            setLinkCards(list_data.link_cards || [])
            eventSource.close()
          }
        } catch (error) {
          console.error('Error processing stream message:', error)
        }
      }

      eventSource.onerror = (error) => {
        console.error('EventSource error:', error)
        eventSource.close()
      }

      return () => {
        if (eventSource.readyState !== EventSource.CLOSED) {
          eventSource.close()
        }
      }
    }
  }, [streamId])

  const handleLinkPress = (link_target_kind: string, link_code: string) => {
    openPageLink(link_target_kind, link_code)
  }

  return (
    <Page
      kind="list"
      title={title}
      headline={headline}
      link_cards={linkCards.map((card) => ({
        ...card,
        onLinkPress: () => handleLinkPress(card.link_target_kind, card.link_code),
      }))}
      showBackButton
      showLoading={loading}
    />
  )
}
