import React, { useState, useEffect } from 'react'
import Taro, { useRouter, useShareAppMessage, useDidShow } from '@tarojs/taro'
import { View, Text, Image, Video, RichText, Input, ScrollView } from '@tarojs/components'
import { AtActivityIndicator, AtIcon } from 'taro-ui'
import { getTopicDetail, createReply, uploadMedia } from '../../../api'
import { marked } from 'marked'
import './detail.scss'

const ForumDetail = () => {
  const router = useRouter()
  const { id } = router.params
  
  const [topic, setTopic] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [replyContent, setReplyContent] = useState('')
  const [sending, setSending] = useState(false)
  const [htmlContent, setHtmlContent] = useState('')
  const [userInfo, setUserInfo] = useState<any>(null)

  const fetchDetail = async () => {
    try {
      const res = await getTopicDetail(Number(id))
      const topicData = res.data || res
      setTopic(topicData)
      
      // Parse markdown
      if (topicData.content) {
          const html = marked.parse(topicData.content)
          // Basic fix for images to fit screen
          const styledHtml = (html as string).replace(/<img/g, '<img style="max-width:100%;border-radius:8px;"')
          setHtmlContent(styledHtml)
      }
    } catch (error) {
      console.error(error)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    const info = Taro.getStorageSync('userInfo')
    if (info) setUserInfo(info)

    if (id) {
        fetchDetail()
    }
  }, [id])

  useDidShow(() => {
      if (id && !loading) {
          fetchDetail()
      }
  })

  useShareAppMessage(() => {
    return {
      title: topic?.title || '技术社区',
      path: `/subpackages/forum/detail/index?id=${id}`
    }
  })

  const handleReplyChange = (e) => {
      setReplyContent(e.detail.value)
  }

  const handleEdit = () => {
      Taro.navigateTo({
          url: `/subpackages/forum/create/index?id=${id}`
      })
  }

  const handleUpload = async () => {
      try {
          const res = await Taro.chooseMedia({
              count: 1,
              mediaType: ['image', 'video'],
              sourceType: ['album', 'camera']
          })
          
          const file = res.tempFiles[0]
          const type = file.fileType === 'video' ? 'video' : 'image'
          
          Taro.showLoading({ title: '上传中...' })
          
          const uploadRes = await uploadMedia(file.tempFilePath, type)
          
          let url = uploadRes.file
          // Ensure full URL if needed (backend usually returns relative or absolute)
          if (url && !url.startsWith('http')) {
             const BASE_URL = (typeof process !== 'undefined' && process.env && process.env.TARO_APP_API_URL) || 'https://market.quant-speed.com/api'
             const host = BASE_URL.replace(/\/api\/?$/, '')
             if (!url.startsWith('/')) url = '/' + url
             url = `${host}${url}`
          }
          
          const insertText = type === 'video'
              ? `\n<video src="${url}" controls width="100%"></video>\n`
              : `\n![image](${url})\n`
              
          setReplyContent(prev => prev + insertText)
          
          Taro.hideLoading()
      } catch (error) {
          console.error(error)
          Taro.hideLoading()
          Taro.showToast({ title: '上传失败', icon: 'none' })
      }
  }

  const handleSubmit = async () => {
      const token = Taro.getStorageSync('token')
      if (!token) {
          Taro.showToast({ title: '请先登录', icon: 'none' })
          return
      }
      
      if (!replyContent.trim()) {
          Taro.showToast({ title: '请输入内容', icon: 'none' })
          return
      }
      
      setSending(true)
      try {
          await createReply({
              topic: Number(id),
              content: replyContent
          })
          Taro.showToast({ title: '回复成功', icon: 'success' })
          setReplyContent('')
          fetchDetail() // Refresh
      } catch (error) {
          console.error(error)
          Taro.showToast({ title: '回复失败', icon: 'none' })
      } finally {
          setSending(false)
      }
  }

  if (loading) return <View className='forum-detail-page'><AtActivityIndicator mode='center' /></View>
  if (!topic) return <View className='forum-detail-page'><View style={{padding: 20, textAlign: 'center'}}>话题不存在</View></View>

  return (
    <View className='forum-detail-page'>
      <ScrollView scrollY style={{height: '100vh'}}>
      <View style={{paddingBottom: 80}}>
      <View className='topic-card'>
        <View className='header'>
            {topic.is_pinned && <Text style={{color: '#ff4d4f', marginRight: 5, fontSize: 12, border: '1px solid #ff4d4f', padding: '0 4px', borderRadius: 4}}>置顶</Text>}
            <Text className='title'>{topic.title}</Text>
            
            <View className='meta'>
                    <View className='author'>
                        <Image className='avatar' src={topic.author_info?.avatar_url || 'https://via.placeholder.com/30'} />
                        <Text style={{fontWeight: 600, color: '#ccc'}}>{topic.author_info?.nickname}</Text>
                        {topic.is_verified_owner && <AtIcon value='check-circle' size='14' color='#00b96b' />}
                    </View>
                    <Text>•</Text>
                    <Text>{new Date(topic.created_at).toLocaleDateString()}</Text>
                    <Text>•</Text>
                    <View style={{display: 'flex', alignItems: 'center'}}>
                        <AtIcon value='eye' size='14' color='#666' style={{marginRight: 4}} />
                        <Text>{topic.view_count}</Text>
                    </View>

                    {userInfo && topic.author === userInfo.id && (
                        <View onClick={handleEdit} style={{display: 'flex', alignItems: 'center', marginLeft: 'auto', padding: '6px 12px', background: 'rgba(0, 185, 107, 0.15)', borderRadius: 20}}>
                            <AtIcon value='edit' size='14' color='#00b96b' />
                            <Text style={{fontSize: 12, color: '#00b96b', marginLeft: 4, fontWeight: 600}}>编辑</Text>
                        </View>
                    )}
                </View>
        </View>
        
        <View className='content'>
            <RichText nodes={htmlContent} />
        </View>

        {topic.media && topic.media.length > 0 && (
            <View className='media-list'>
                {topic.media.filter(m => m.media_type === 'video').map(m => (
                    <View key={m.id} className='media-item'>
                        <Video src={m.url} controls />
                    </View>
                ))}
            </View>
        )}
      </View>

      <View className='replies-section'>
        <View className='section-title'>{topic.replies?.length || 0} 条回复</View>
        
        {topic.replies?.map((reply, idx) => (
            <View key={reply.id} className='reply-card'>
                <Image className='avatar' src={reply.author_info?.avatar_url || 'https://via.placeholder.com/30'} />
                <View className='reply-main'>
                    <View className='reply-header'>
                        <View style={{display: 'flex', flexDirection: 'column'}}>
                             <Text className='nickname'>{reply.author_info?.nickname}</Text>
                             <Text style={{fontSize: 10, color: '#666', marginTop: 2}}>#{idx + 1} • {new Date(reply.created_at).toLocaleDateString()}</Text>
                        </View>
                        <AtIcon value='message' size='14' color='#444' />
                    </View>
                    <View className='reply-content'>
                        {/* Simple markdown render for replies or just text if complex */}
                        <RichText nodes={marked.parse(reply.content) as string} />
                    </View>
                </View>
            </View>
        ))}
      </View>
      </View>
      </ScrollView>

      <View className='reply-bar'>
        <View className='action-btn' onClick={handleUpload}>
            <AtIcon value='image' size='20' color='#888' />
        </View>
        <View className='input-wrapper'>
            <Input 
                value={replyContent}
                onInput={handleReplyChange}
                placeholder='发表回复...'
                confirmType='send'
                onConfirm={handleSubmit}
            />
        </View>
        <View className='action-btn' onClick={handleSubmit}>
            {sending ? <AtActivityIndicator size={20} /> : <Text className='send-btn'>发送</Text>}
        </View>
      </View>
    </View>
  )
}

export default ForumDetail
