import { useEffect, useRef, useState } from 'react'
import type { Post } from '~/lib/api-client'
import PostCard from '~/components/PostCard'
import EmptyState from '~/components/EmptyState'

const PAGE_SIZE = 10

export default function PostList({
  posts,
  handle,
  error,
}: {
  posts: Post[] | null
  handle: string
  error?: string | null
}) {
  const [visibleCount, setVisibleCount] = useState(PAGE_SIZE)
  const sentinelRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    setVisibleCount(PAGE_SIZE)
  }, [posts])

  useEffect(() => {
    const sentinel = sentinelRef.current
    if (!sentinel || !posts || visibleCount >= posts.length) return
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) setVisibleCount((n) => n + PAGE_SIZE)
    })
    observer.observe(sentinel)
    return () => observer.disconnect()
  }, [posts, visibleCount])

  if (error) return <p className="text-sm text-red-500">{error}</p>

  if (posts === null) return null

  if (posts.length === 0)
    return (
      <EmptyState message="Nothing published yet." detail="Write your first article to get started." />
    )

  const visible = posts.slice(0, visibleCount)

  return (
    <>
      <ul className="space-y-2.5">
        {visible.map((post) => {
          const rkey = post.atUri.split('/').pop()!
          const did = post.atUri.split('/')[2]
          const isDraft = post.visibility !== 'published'
          const draftPubRkey = post.resolvedUrl
            ? new URL(post.resolvedUrl).pathname.split('/').pop()!
            : null
          const editTo = isDraft && draftPubRkey
            ? `/${encodeURIComponent(handle)}/pub/${draftPubRkey}/${encodeURIComponent(rkey)}/edit`
            : undefined

          return (
            <PostCard
              key={post.sk}
              authorDid={did}
              rkey={rkey}
              title={post.title}
              publishedAt={post.publishedAt}
              publicationName={post.resolvedPubName}
              coverImageCid={post.coverImageRef}
              resolvedUrl={post.resolvedUrl}
              path={post.path}
              textContent={post.textContent}
              description={post.description}
              isDraft={isDraft}
              editTo={editTo}
            />
          )
        })}
      </ul>
      <div ref={sentinelRef} />
    </>
  )
}
