import { useEffect, useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import { ScrollView, Text, View } from '@tarojs/components'
import { useSystemLayout } from '@/hooks/useSystemLayout'
import Icon from '@/components/ui/Icon'
import PostCard from '@/features/feed/components/PostCard'
import ToastOverlay from '@/components/feedback/ToastOverlay'
import { deletePost, getUserPosts, setPostLike } from '@/services/feed.service'
import { useToast } from '@/hooks/useToast'
import { useRefreshOnShow } from '@/hooks/useRefreshOnShow'
import { cachePost, markFresh, onPostLike } from '@/store/dataBus'
import { ensureProfileReady } from '@/store/session.store'
import type { Post } from '@/types/domain'
import './index.scss'

const PAGE_SIZE = 20

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

export default function MyPostsPage() {
  const { statusBarHeight } = useSystemLayout()
  const [posts, setPosts] = useState<Post[]>([])
  const [nextCursor, setNextCursor] = useState('')
  const [loading, setLoading] = useState(true)
  const [loadingMore, setLoadingMore] = useState(false)
  const toast = useToast(480)
  const postsRef = useRef<Post[]>([])
  const pendingLikeIds = useRef(new Set<string>())

  const load = (silent = false, append = false, cursor = '') => {
    if (append) setLoadingMore(true)
    else if (!silent) setLoading(true)

    getUserPosts({ cursor, pageSize: PAGE_SIZE })
      .then(list => {
        setPosts(current => (append ? mergePosts(current, list.list) : list.list))
        setNextCursor(list.nextCursor || '')
        if (!append) markFresh('myPosts')
      })
      .finally(() => {
        if (append) setLoadingMore(false)
        else if (!silent) setLoading(false)
      })
  }

  useEffect(() => {
    load()
  }, [])

  useEffect(() => {
    postsRef.current = posts
  }, [posts])

  // Refresh on return only when stale (e.g. after publishing), silently.
  useRefreshOnShow('myPosts', () => load(true))

  // Stay in sync when the same post is liked elsewhere (plaza / detail page).
  useEffect(() => onPostLike(({ postId, liked, likes }) => {
    setPosts(current => current.map(post => (
      post._id === postId
        ? post.likedByMe === liked && post.counts.likes === likes
          ? post
          : { ...post, likedByMe: liked, counts: { ...post.counts, likes } }
        : post
    )))
  }), [])

  const loadMore = () => {
    if (loading || loadingMore || !nextCursor) return
    load(true, true, nextCursor)
  }

  const confirmDelete = (post: Post) => {
    Taro.showModal({
      title: '删除动态',
      content: '确定删除这条动态吗？此操作不可恢复。',
      confirmText: '删除',
      confirmColor: '#ff8a9b',
      success: async res => {
        if (!res.confirm) return
        const snapshot = postsRef.current
        setPosts(current => current.filter(item => item._id !== post._id)) // optimistic
        try {
          await deletePost(post._id)
          Taro.showToast({ title: '已删除', icon: 'none' })
        } catch {
          setPosts(snapshot) // rollback
          Taro.showToast({ title: '删除失败，请重试', icon: 'none' })
        }
      }
    })
  }

  const openMore = (postId: string) => {
    const post = postsRef.current.find(item => item._id === postId)
    if (!post) return
    Taro.showActionSheet({ itemList: ['编辑', '删除'] })
      .then(res => {
        if (res.tapIndex === 0) {
          cachePost(post)
          Taro.navigateTo({ url: `/pages/post-edit/index?postId=${postId}` })
        } else if (res.tapIndex === 1) {
          confirmDelete(post)
        }
      })
      .catch(() => undefined) // user dismissed the sheet
  }

  const likePost = async (postId: string) => {
    if (!(await ensureProfileReady())) return
    if (pendingLikeIds.current.has(postId)) return
    const previousPost = postsRef.current.find(post => post._id === postId)
    if (!previousPost) return

    const likedByMe = !previousPost.likedByMe
    const likes = Math.max(0, previousPost.counts.likes + (likedByMe ? 1 : -1))
    pendingLikeIds.current.add(postId)
    if (likedByMe) toast.show()
    setPosts(current => current.map(post => (
      post._id === postId
        ? { ...post, likedByMe, counts: { ...post.counts, likes } }
        : post
    )))

    try {
      const result = await setPostLike(postId, likedByMe)
      setPosts(current => current.map(post => (
        post._id === postId
          ? { ...post, likedByMe: result.liked, counts: { ...post.counts, likes: result.likes } }
          : post
      )))
    } catch {
      setPosts(current => current.map(post => (
        post._id === postId
          ? {
            ...post,
            likedByMe: previousPost.likedByMe,
            counts: { ...post.counts, likes: previousPost.counts.likes }
          }
          : post
      )))
      Taro.showToast({ title: '点赞失败，请重试', icon: 'none' })
    } finally {
      pendingLikeIds.current.delete(postId)
    }
  }

  return (
    <View className='my-posts'>
      <View className='my-posts__nav' style={{ paddingTop: `${statusBarHeight}px` }}>
        <View className='my-posts__nav-row'>
          <View className='my-posts__back' onClick={() => Taro.navigateBack()}>
            <Icon name='chev' size={22} className='my-posts__back-icon' />
          </View>
          <Text className='my-posts__title'>我的动态</Text>
          <View className='my-posts__nav-spacer' />
        </View>
      </View>

      <ScrollView
        scrollY
        className='my-posts__scroll'
        enhanced
        showScrollbar={false}
        lowerThreshold={120}
        onScrollToLower={loadMore}
      >
        <View className='my-posts__feed'>
          {posts.map(post => (
            <PostCard
              key={post._id}
              post={post}
              onLike={likePost}
              onOpen={id => {
                cachePost(post)
                Taro.navigateTo({ url: `/pages/post-detail/index?postId=${id}` })
              }}
              onMore={openMore}
            />
          ))}
          {loading && posts.length === 0 ? (
            <Text className='my-posts__empty'>加载中…</Text>
          ) : !loading && posts.length === 0 ? (
            <Text className='my-posts__empty'>还没有发布过动态，去广场点 + 发布第一条吧</Text>
          ) : loadingMore ? (
            <Text className='my-posts__empty'>加载更多中…</Text>
          ) : posts.length > 0 && !nextCursor ? (
            <Text className='my-posts__empty'>暂时没有更多了</Text>
          ) : null}
        </View>
      </ScrollView>

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