import { useEffect, useRef, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { ScrollView, Text, View } from '@tarojs/components'
import CustomNavBar from '@/components/layout/CustomNavBar'
import PageShell from '@/components/layout/PageShell'
import BottomTabBar from '@/components/navigation/BottomTabBar'
import SearchBar from '@/components/ui/SearchBar'
import SegmentedTabs from '@/components/ui/SegmentedTabs'
import Chip from '@/components/ui/Chip'
import ToastOverlay from '@/components/feedback/ToastOverlay'
import FeedAdCard from '@/features/feed/components/FeedAdCard'
import PostCard from '@/features/feed/components/PostCard'
import { getFeedList, setPostLike } from '@/services/feed.service'
import { useToast } from '@/hooks/useToast'
import type { FeedChannel, Post } from '@/types/domain'
import './index.scss'

const tabs = [
  { key: 'feed', label: '推荐' },
  { key: 'nearby', label: '附近' },
  { key: 'follow', label: '关注' }
] as const

const topics = ['全部', '滨江公园', '金毛日常', '猫咪', '周末聚会', '新手养宠']

export default function PlazaPage() {
  const [channel, setChannel] = useState<FeedChannel>('feed')
  const [topic, setTopic] = useState('全部')
  const [posts, setPosts] = useState<Post[]>([])
  const [loading, setLoading] = useState(true)
  const toast = useToast(480)
  const firstShow = useRef(true)

  const loadFeed = () => {
    setLoading(true)
    getFeedList(channel, topic === '全部' ? undefined : topic)
      .then(setPosts)
      .finally(() => setLoading(false))
  }

  useEffect(() => {
    loadFeed()
  }, [channel, topic])

  // Refresh when returning to the tab (e.g. after publishing a new post).
  useDidShow(() => {
    if (firstShow.current) {
      firstShow.current = false
      return
    }
    loadFeed()
  })

  const likePost = async (postId: string) => {
    const previousPosts = posts
    const nextPosts = 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(nextPosts)
    const next = nextPosts.find(post => post._id === postId)
    if (!next) return

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

  const openPost = (postId: string) => {
    Taro.navigateTo({ url: `/pages/post-detail/index?postId=${postId}` })
  }

  return (
    <PageShell className='plaza-page'>
      <CustomNavBar title='广场' />
      <SearchBar placeholder='搜索话题、宠物、附近活动' />
      <SegmentedTabs items={tabs as any} value={channel} onChange={setChannel} />
      <ScrollView scrollX className='plaza-page__chips' showScrollbar={false}>
        <View className='plaza-page__chips-inner'>
          {topics.map(item => (
            <Chip key={item} active={topic === item} onClick={() => setTopic(item)}>
              {item}
            </Chip>
          ))}
        </View>
      </ScrollView>
      <View className='plaza-page__feed'>
        {posts.map((post, index) => (
          <View key={post._id}>
            <PostCard post={post} onLike={likePost} onOpen={openPost} />
            {index === 0 ? <FeedAdCard /> : null}
          </View>
        ))}
        {loading && posts.length === 0 ? (
          <Text className='plaza-page__empty'>加载中…</Text>
        ) : !loading && posts.length === 0 ? (
          <Text className='plaza-page__empty'>
            {channel === 'follow' ? '关注的人还没有发布动态，去发现更多汪友吧' : '还没有动态，点击 + 发布第一条吧'}
          </Text>
        ) : (
          <Text className='plaza-page__empty'>暂时没有更多了，稍后再来看看吧</Text>
        )}
      </View>
      <ToastOverlay visible={toast.visible} />
      <BottomTabBar active='plaza' />
    </PageShell>
  )
}
