import { useEffect, useState } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { ScrollView, Text, Textarea, View } from '@tarojs/components'
import { useSystemLayout } from '@/hooks/useSystemLayout'
import Icon from '@/components/ui/Icon'
import VisibilitySheet from '@/features/publish/components/VisibilitySheet'
import { getPostDetail, updatePost } from '@/services/feed.service'
import { getCachedPost } from '@/store/dataBus'
import type { Visibility } from '@/types/domain'
import './index.scss'

const VISIBILITY_LABEL: Record<Visibility, string> = {
  public: '公开',
  friends: '汪友可见',
  private: '仅自己'
}

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

  const [content, setContent] = useState(cached?.body || '')
  const [visibility, setVisibility] = useState<Visibility>(cached?.visibility || 'public')
  const [visSheet, setVisSheet] = useState(false)
  const [saving, setSaving] = useState(false)

  // Fall back to a fetch only if we arrived without a cached post (e.g. a cold
  // deep-link). The normal path from 我的动态 always seeds the cache first.
  useEffect(() => {
    if (cached || !postId) return
    getPostDetail(postId)
      .then(({ post }) => {
        if (!post) return
        setContent(post.body || '')
        setVisibility(post.visibility || 'public')
      })
      .catch(() => undefined)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const length = content.trim().length
  const canSave = length > 0 && length <= 2000

  const save = async () => {
    if (saving) return
    if (!canSave) {
      Taro.showToast({ title: length ? '正文最多 2000 字' : '写点什么吧', icon: 'none' })
      return
    }
    setSaving(true)
    try {
      await updatePost(postId, { content: content.trim(), visibility })
      Taro.showToast({ title: '已保存', icon: 'success' })
      setTimeout(() => Taro.navigateBack(), 500)
    } catch {
      Taro.showToast({ title: '保存失败，请重试', icon: 'none' })
    } finally {
      setSaving(false)
    }
  }

  return (
    <View className='post-edit'>
      <View className='post-edit__nav' style={{ paddingTop: `${statusBarHeight}px` }}>
        <View className='post-edit__nav-row'>
          <View className='post-edit__close' onClick={() => Taro.navigateBack()}>
            <Icon name='close' size={22} />
          </View>
          <Text className='post-edit__nav-title'>编辑动态</Text>
          {/* Right side kept clear so the title doesn't sit under WeChat's capsule. */}
          <View className='post-edit__nav-spacer' />
        </View>
      </View>

      <ScrollView scrollY className='post-edit__body' enhanced showScrollbar={false}>
        <Textarea
          className='post-edit__textarea'
          value={content}
          placeholder='说点什么…'
          placeholderClass='post-edit__placeholder'
          maxlength={2000}
          autoHeight
          onInput={e => setContent(e.detail.value)}
        />
        <Text className='post-edit__count'>{length}/2000</Text>

        <View className='post-edit__row' onClick={() => setVisSheet(true)}>
          <Text className='post-edit__row-label'>可见范围</Text>
          <View className='post-edit__row-value'>
            <Text>{VISIBILITY_LABEL[visibility]}</Text>
            <Icon name='chev' size={16} />
          </View>
        </View>

        <Text className='post-edit__hint'>此处仅编辑文字与可见范围；如需修改图片或话题，请删除后重新发布。</Text>
      </ScrollView>

      <View className='post-edit__footer' style={{ paddingBottom: `${Math.max(16, safeBottom)}px` }}>
        <View
          className={`post-edit__submit ${canSave && !saving ? '' : 'post-edit__submit--disabled'}`}
          onClick={save}
        >
          {saving ? '保存中…' : '保存'}
        </View>
      </View>

      <VisibilitySheet visible={visSheet} value={visibility} onChange={setVisibility} onClose={() => setVisSheet(false)} />
    </View>
  )
}
