import { useEffect, useState } from 'react'
import Taro, { useDidShow } 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 { getUserPosts, setPostLike } from '@/services/feed.service'
import { useToast } from '@/hooks/useToast'
import type { Post } from '@/types/domain'
import './index.scss'

export default function MyPostsPage() {
  const { statusBarHeight } = useSystemLayout()
  const [posts, setPosts] = useState<Post[]>([])
  const [loading, setLoading] = useState(true)
  const toast = useToast(480)

  const load = () => {
    setLoading(true)
    getUserPosts()
      .then(setPosts)
      .finally(() => setLoading(false))
  }

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

  // Refresh on return (e.g. after publishing a new post).
  useDidShow(load)

  const likePost = async (postId: string) => {
    const next = posts.map(post => {
      if (post._id !== postId) return post
      const likedByMe = !post.likedByMe
      if (likedByMe) toast.show()
      return {
        ...post,
        likedByMe,
        counts: { ...post.counts, likes: Math.max(0, post.counts.likes + (likedByMe ? 1 : -1)) }
      }
    })
    setPosts(next)
    const target = next.find(p => p._id === postId)
    if (target) await setPostLike(postId, target.likedByMe)
  }

  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}>
        <View className='my-posts__feed'>
          {posts.map(post => (
            <PostCard
              key={post._id}
              post={post}
              onLike={likePost}
              onOpen={id => Taro.navigateTo({ url: `/pages/post-detail/index?postId=${id}` })}
            />
          ))}
          {loading && posts.length === 0 ? (
            <Text className='my-posts__empty'>加载中…</Text>
          ) : !loading && posts.length === 0 ? (
            <Text className='my-posts__empty'>还没有发布过动态，去广场点 + 发布第一条吧</Text>
          ) : null}
        </View>
      </ScrollView>

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