import { useEffect, 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 type { Post, PostComment } from '@/types/domain'
import './index.scss'

export default function PostDetailPage() {
  const { statusBarHeight, safeBottom } = useSystemLayout()
  const router = useRouter()
  const postId = router.params.postId || ''

  const [post, setPost] = useState<Post | null>(null)
  const [comments, setComments] = useState<PostComment[]>([])
  const [loading, setLoading] = useState(true)
  const [draft, setDraft] = useState('')
  const [sending, setSending] = useState(false)
  const toast = useToast(480)

  const load = () => {
    if (!postId) {
      setLoading(false)
      return
    }
    setLoading(true)
    getPostDetail(postId)
      .then(res => {
        setPost(res.post)
        setComments(res.comments)
      })
      .finally(() => setLoading(false))
  }

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

  const likePost = async (id: string) => {
    if (!post) return
    const likedByMe = !post.likedByMe
    if (likedByMe) toast.show()
    const next = {
      ...post,
      likedByMe,
      counts: { ...post.counts, likes: Math.max(0, post.counts.likes + (likedByMe ? 1 : -1)) }
    }
    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(post)
      Taro.showToast({ title: '点赞失败，请重试', icon: 'none' })
    }
  }

  const send = async () => {
    const content = draft.trim()
    if (!content || sending || !post) return
    setSending(true)
    setDraft('')
    try {
      const result = await createPostComment(post._id, content)
      setComments(current => [
        ...current,
        {
          _id: result.commentId,
          author: {
            id: 'me',
            name: '我',
            avatarKey: 'gradient-avatar-1'
          },
          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>

          {loading && !post ? (
            <Text className='post-detail__empty'>加载中…</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>
            ))
          )}
        </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>
  )
}
