import { useEffect, useRef, useState } from 'react'
import { useAuth } from '~/lib/auth-context'
import { SITE_NAME } from '~/lib/site-config'
import { getTimeline, type TimelineItem } from '~/lib/api-client'
import CenteredMessage from '~/components/CenteredMessage'
import EmptyState from '~/components/EmptyState'
import PageLayout from '~/components/PageLayout'
import PostCard from '~/components/PostCard'
import Spinner from '~/components/Spinner'

export function meta() {
  return [{ title: `Following — ${SITE_NAME}` }]
}

export default function Following() {
  const { session, loading: authLoading } = useAuth()
  const [items, setItems] = useState<TimelineItem[]>([])
  const [cursor, setCursor] = useState<string | null | undefined>(undefined)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const sentinelRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (authLoading || !session) return
    let cancelled = false
    setLoading(true)
    getTimeline(session)
      .then((page) => {
        if (cancelled) return
        setItems(page.items)
        setCursor(page.cursor)
      })
      .catch((err) => {
        if (!cancelled) setError(err instanceof Error ? err.message : 'Failed to load')
      })
      .finally(() => { if (!cancelled) setLoading(false) })
    return () => { cancelled = true }
  }, [session, authLoading])

  useEffect(() => {
    if (!session || cursor == null || !sentinelRef.current) return
    const sentinel = sentinelRef.current
    const observer = new IntersectionObserver((entries) => {
      if (!entries[0].isIntersecting) return
      observer.disconnect()
      setLoading(true)
      getTimeline(session, cursor)
        .then((page) => {
          setItems((prev) => [...prev, ...page.items])
          setCursor(page.cursor)
        })
        .catch((err) => setError(err instanceof Error ? err.message : 'Failed to load more'))
        .finally(() => setLoading(false))
    })
    observer.observe(sentinel)
    return () => observer.disconnect()
  }, [session, cursor])

  if (authLoading) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <Spinner />
      </div>
    )
  }

  if (!session) {
    return <CenteredMessage message="Sign in to see articles from publications you follow." action={{ label: 'Sign in', to: '/' }} />
  }

  return (
    <PageLayout>
        <div>
          <h1 className="font-display text-2xl font-semibold text-stone-900 dark:text-white">Following</h1>
          <p className="text-sm text-stone-500 dark:text-stone-400 mt-1">Articles from publications you follow</p>
        </div>

        {error && <p className="text-sm text-red-500">{error}</p>}

        {cursor === undefined && loading && (
          <div className="flex justify-center py-12">
            <Spinner />
          </div>
        )}

        {cursor !== undefined && items.length === 0 && !loading && (
          <EmptyState
            message="Nothing here yet."
            detail="Visit an author's profile and subscribe to their publication to see their articles here."
          />
        )}

        <ul className="space-y-2.5">
          {items.map((item) => (
            <PostCard
              key={`${item.authorDid}/${item.rkey}`}
              authorDid={item.authorDid}
              rkey={item.rkey}
              pubRkey={item.pubAtUri?.split('/').pop()}
              title={item.title}
              publishedAt={item.publishedAt}
              resolvedHandle={item.resolvedHandle}
              publicationName={item.publicationName}
              coverImageCid={item.coverImageCid}
              resolvedUrl={item.resolvedUrl}
              path={item.path}
              textContent={item.textContent}
              description={item.description}
            />
          ))}
        </ul>

        <div ref={sentinelRef} />

        {loading && cursor !== undefined && (
          <div className="flex justify-center py-4">
            <Spinner size="md" />
          </div>
        )}

        {cursor === null && items.length > 0 && (
          <p className="text-center text-sm text-stone-400 dark:text-stone-600 py-4">
            You've reached the end.
          </p>
        )}
    </PageLayout>
  )
}
