import { useEffect, useRef, useState } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { Input, ScrollView, Text, View } from '@tarojs/components'
import { useSystemLayout } from '@/hooks/useSystemLayout'
import Icon from '@/components/ui/Icon'
import Avatar from '@/components/ui/Avatar'
import PostCard from '@/features/feed/components/PostCard'
import ToastOverlay from '@/components/feedback/ToastOverlay'
import { createPostComment, getPostDetail, setPostLike } from '@/services/feed.service'
import { useToast } from '@/hooks/useToast'
import { cachePost, getCachedPost } from '@/store/dataBus'
import { ensureProfileReady, useSession } from '@/store/session.store'
import type { Post, PostComment } from '@/types/domain'
import './index.scss'

const COMMENTS_PAGE_SIZE = 50

function mergeComments(current: PostComment[], incoming: PostComment[]): PostComment[] {
  const seen = new Set(current.map(comment => comment._id))
  return [...current, ...incoming.filter(comment => !seen.has(comment._id))]
}

export default function PostDetailPage() {
  const { statusBarHeight, safeBottom } = useSystemLayout()
  const router = useRouter()
  const postId = router.params.postId || ''
  const { user } = useSession()
  // Paint immediately from the post the list already loaded (same image URLs →
  // cached, no reload); only show a loader on a cold deep-link entry.
  const cachedPost = getCachedPost(postId)

  const [post, setPost] = useState<Post | null>(cachedPost || null)
  const [comments, setComments] = useState<PostComment[]>([])
  const [commentsLoaded, setCommentsLoaded] = useState(false)
  const [commentsError, setCommentsError] = useState(false)
  const [commentsNextCursor, setCommentsNextCursor] = useState('')
  const [loadingCommentsMore, setLoadingCommentsMore] = useState(false)
  const [draft, setDraft] = useState('')
  const [sending, setSending] = useState(false)
  const toast = useToast(480)
  const postRef = useRef<Post | null>(cachedPost || null)
  const pendingLikeIds = useRef(new Set<string>())

  useEffect(() => {
    postRef.current = post
  }, [post])

  const load = (appendComments = false, commentCursor = '') => {
    if (!postId) {
      setCommentsLoaded(true)
      return
    }
    if (appendComments) setLoadingCommentsMore(true)
    else {
      setCommentsError(false)
      setCommentsLoaded(false)
    }
    // No loading flag flip: keep the cached post/images visible while refreshing.
    getPostDetail({ postId, commentCursor, commentPageSize: COMMENTS_PAGE_SIZE })
      .then(res => {
        const freshPost = res.post
        if (freshPost) {
          cachePost(freshPost)
          // Keep the cached post reference stable unless its counts actually
          // changed. Replacing it wholesale re-renders (and visibly re-paints)
          // the post card every time comments arrive — that was the flash.
          setPost(prev => {
            if (!prev) return freshPost
            if (
              prev.likedByMe === freshPost.likedByMe &&
              prev.counts.likes === freshPost.counts.likes &&
              prev.counts.comments === freshPost.counts.comments
            ) {
              return prev
            }
            return { ...prev, likedByMe: freshPost.likedByMe, counts: freshPost.counts }
          })
        }
        setComments(current => (appendComments ? mergeComments(current, res.comments) : res.comments))
        setCommentsNextCursor(res.commentsNextCursor || '')
      })
      .catch(() => {
        if (appendComments) Taro.showToast({ title: '评论加载失败，请重试', icon: 'none' })
        else setCommentsError(true)
      })
      .finally(() => {
        if (appendComments) setLoadingCommentsMore(false)
        else setCommentsLoaded(true)
      })
  }

  useEffect(() => {
    load()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [postId])

  const likePost = async (id: string) => {
    if (!(await ensureProfileReady())) return
    if (pendingLikeIds.current.has(id)) return
    const previousPost = postRef.current
    if (!previousPost) return

    const likedByMe = !previousPost.likedByMe
    if (likedByMe) toast.show()
    const next = {
      ...previousPost,
      likedByMe,
      counts: { ...previousPost.counts, likes: Math.max(0, previousPost.counts.likes + (likedByMe ? 1 : -1)) }
    }
    pendingLikeIds.current.add(id)
    setPost(next)
    try {
      const result = await setPostLike(id, likedByMe)
      setPost(current =>
        current ? { ...current, likedByMe: result.liked, counts: { ...current.counts, likes: result.likes } } : current
      )
    } catch {
      setPost(previousPost)
      Taro.showToast({ title: '点赞失败，请重试', icon: 'none' })
    } finally {
      pendingLikeIds.current.delete(id)
    }
  }

  const send = async () => {
    const content = draft.trim()
    if (!content || sending || !post) return
    if (!(await ensureProfileReady())) return
    setSending(true)
    setDraft('')
    try {
      const result = await createPostComment(post._id, content)
      setComments(current => [
        ...current,
        {
          _id: result.commentId,
          author: {
            id: user._id,
            name: user.nickname || '我',
            avatarKey: user.avatarKey || 'gradient-avatar-1',
            avatarUrl: user.avatarUrl
          },
          content,
          timeText: '刚刚'
        }
      ])
      setPost(current =>
        current ? { ...current, counts: { ...current.counts, comments: result.comments } } : current
      )
    } catch {
      Taro.showToast({ title: '评论失败，请重试', icon: 'none' })
      setDraft(content)
    } finally {
      setSending(false)
    }
  }

  return (
    <View className='post-detail'>
      <View className='post-detail__nav' style={{ paddingTop: `${statusBarHeight}px` }}>
        <View className='post-detail__nav-row'>
          <View className='post-detail__back' onClick={() => Taro.navigateBack()}>
            <Icon name='chev' size={22} className='post-detail__back-icon' />
          </View>
          <Text className='post-detail__title'>动态详情</Text>
          <View className='post-detail__nav-spacer' />
        </View>
      </View>

      <ScrollView scrollY className='post-detail__scroll' enhanced showScrollbar={false}>
        {post ? (
          <View className='post-detail__post'>
            <PostCard post={post} onLike={likePost} enableImagePreview />
          </View>
        ) : null}

        <View className='post-detail__comments'>
          <Text className='post-detail__comments-title'>
            评论{post ? ` ${post.counts.comments}` : ''}
          </Text>

          {!commentsLoaded ? (
            <Text className='post-detail__empty'>{post ? '评论加载中…' : '加载中…'}</Text>
          ) : commentsError ? (
            <Text className='post-detail__empty' onClick={() => load()}>
              评论加载失败，点击重试
            </Text>
          ) : comments.length === 0 ? (
            <Text className='post-detail__empty'>还没有评论，来抢沙发吧</Text>
          ) : (
            <>
              {comments.map(comment => (
                <View key={comment._id} className='post-detail__comment'>
                  <Avatar avatarKey={comment.author.avatarKey} avatarUrl={comment.author.avatarUrl} size='sm' />
                  <View className='post-detail__comment-body'>
                    <View className='post-detail__comment-head'>
                      <Text className='post-detail__comment-name'>{comment.author.name}</Text>
                      <Text className='post-detail__comment-time'>{comment.timeText}</Text>
                    </View>
                    <Text className='post-detail__comment-text'>{comment.content}</Text>
                  </View>
                </View>
              ))}
              {loadingCommentsMore ? (
                <Text className='post-detail__empty'>加载更多评论中…</Text>
              ) : commentsNextCursor ? (
                <Text className='post-detail__empty' onClick={() => load(true, commentsNextCursor)}>
                  加载更多评论
                </Text>
              ) : null}
            </>
          )}
        </View>
      </ScrollView>

      <View className='post-detail__input-bar' style={{ paddingBottom: `${Math.max(12, safeBottom)}px` }}>
        <Input
          className='post-detail__input'
          value={draft}
          placeholder='写评论…'
          placeholderClass='post-detail__input-ph'
          confirmType='send'
          onInput={e => setDraft(e.detail.value)}
          onConfirm={send}
        />
        <View
          className={`post-detail__send ${draft.trim() ? '' : 'post-detail__send--disabled'}`}
          onClick={send}
        >
          发送
        </View>
      </View>

      <ToastOverlay visible={toast.visible} />
    </View>
  )
}
