import React, { useState, useEffect } from 'react'
import Taro, { useRouter, useShareAppMessage, useShareTimeline, useDidShow } from '@tarojs/taro'
import { View, Text, Image, Video, Input, ScrollView } from '@tarojs/components'
import { AtActivityIndicator, AtIcon, AtActionSheet, AtActionSheetItem, AtFloatLayout } from 'taro-ui'
import { getTopicDetail, createReply, uploadMedia, getStarUsers, likeTopic, likeReply } from '../../../api'
import MarkdownReader from '../../../components/MarkdownReader'
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 [userInfo, setUserInfo] = useState<any>(null)
  
  // Star Users & Mention
  const [starUsers, setStarUsers] = useState<any[]>([])
  const [showStarUsers, setShowStarUsers] = useState(false)

  // Expert Detail
  const [showExpert, setShowExpert] = useState(false)
  const [selectedExpert, setSelectedExpert] = useState<any>(null)

  const fetchDetail = async () => {
    try {
      const res = await getTopicDetail(Number(id))
      const topicData = res.data || res
      setTopic(topicData)
    } catch (error) {
      console.error(error)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const fetchStarUsers = async () => {
      try {
          const res = await getStarUsers()
          // API might return array directly or { data: [] }
          const users = Array.isArray(res) ? res : (res.data || [])
          setStarUsers(users)
      } catch (error) {
          console.error('Fetch star users failed', error)
      }
  }

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

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

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

  const handleReplyToUser = (nickname) => {
      const mentionText = `@${nickname} `
      setReplyContent(prev => prev + mentionText)
      setShowStarUsers(false)
  }

  const handleLikeTopic = async () => {
    const token = Taro.getStorageSync('token')
    if (!token) {
        Taro.showToast({ title: '请先登录', icon: 'none' })
        return
    }
    try {
        const res = await likeTopic(topic.id)
        const data = res.data || res
        setTopic(prev => ({
            ...prev,
            is_liked: data.liked,
            like_count: data.count
        }))
    } catch (error) {
        Taro.showToast({ title: '操作失败', icon: 'none' })
    }
  }

  const handleLikeReply = async (replyId) => {
    const token = Taro.getStorageSync('token')
    if (!token) {
        Taro.showToast({ title: '请先登录', icon: 'none' })
        return
    }
    try {
        const res = await likeReply(replyId)
        const data = res.data || res
        setTopic(prev => ({
            ...prev,
            replies: prev.replies.map(r => {
                if (r.id === replyId) {
                    return { ...r, is_liked: data.liked, like_count: data.count }
                }
                return r
            })
        }))
    } catch (error) {
        Taro.showToast({ title: '操作失败', icon: 'none' })
    }
  }

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

  // 分享到朋友圈
  useShareTimeline(() => {
    return {
      title: topic?.title || '技术社区',
      query: `id=${id}`,
      imageUrl: topic?.author_info?.avatar_url || 'https://via.placeholder.com/300x300?text=技术社区'
    }
  })

  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>

  const showUserTitle = (e, user) => {
      e.stopPropagation()
      if (user.is_star || user.title) {
          setSelectedExpert(user)
          setShowExpert(true)
      }
  }

  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' onClick={(e) => showUserTitle(e, topic.author_info)}>
                        <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>
                    <View className={`like-btn ${topic.is_liked ? 'active' : ''}`} onClick={handleLikeTopic}>
                        <AtIcon value={topic.is_liked ? 'heart-2' : 'heart'} size='18' color={topic.is_liked ? '#ff4d4f' : '#888'} />
                        <Text>{topic.like_count || 0}</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'>
            <MarkdownReader content={topic.content} />
        </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'} onClick={(e) => showUserTitle(e, reply.author_info)} />
                <View className='reply-main'>
                    <View className='reply-header'>
                        <View style={{display: 'flex', flexDirection: 'column'}}>
                             <View style={{display: 'flex', alignItems: 'center'}}>
                                <Text className='nickname'>{reply.author_info?.nickname}</Text>
                                {reply.is_pinned && <Text style={{color: '#ff4d4f', marginLeft: 4, fontSize: 10, border: '1px solid #ff4d4f', padding: '0 4px', borderRadius: 4}}>置顶</Text>}
                             </View>
                             <Text style={{fontSize: 10, color: '#666', marginTop: 2}}>#{idx + 1} • {new Date(reply.created_at).toLocaleDateString()}</Text>
                        </View>
                        <View className='reply-actions'>
                            <View className={`reply-like-btn ${reply.is_liked ? 'active' : ''}`} onClick={() => handleLikeReply(reply.id)}>
                                <AtIcon value={reply.is_liked ? 'heart-2' : 'heart'} size='14' color={reply.is_liked ? '#ff4d4f' : '#888'} />
                                <Text>{reply.like_count || 0}</Text>
                            </View>
                            <View className='reply-to-btn' onClick={() => handleReplyToUser(reply.author_info?.nickname)}>
                                <Text>回复</Text>
                            </View>
                            <AtIcon value='message' size='14' color='#666' />
                        </View>
                    </View>
                    <View className='reply-content'>
                        <MarkdownReader content={reply.content} />
                    </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='action-btn' onClick={() => setShowStarUsers(true)} style={{marginLeft: 0}}>
            <AtIcon value='at' 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>

      <AtActionSheet isOpened={showStarUsers} cancelText='取消' title='选择要@的技术专家' onCancel={() => setShowStarUsers(false)} onClose={() => setShowStarUsers(false)}>
        {starUsers.map(user => (
            <AtActionSheetItem key={user.id} onClick={() => handleReplyToUser(user.nickname)}>
                <View style={{display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
                    <Image src={user.avatar_url || 'https://via.placeholder.com/30'} style={{width: 24, height: 24, borderRadius: 12, marginRight: 8}} />
                    <Text>{user.nickname}</Text>
                    <Text style={{fontSize: 10, color: '#999', marginLeft: 4}}>({user.title || '专家'})</Text>
                </View>
            </AtActionSheetItem>
        ))}
      </AtActionSheet>

      <AtFloatLayout isOpened={showExpert} title="技术专家信息" onClose={() => setShowExpert(false)}>
        {selectedExpert && (
            <View className='expert-modal-content'>
                <View className='expert-header'>
                    <View className='avatar-container'>
                        <Image src={selectedExpert.avatar_url} className='expert-avatar' />
                        <View className='avatar-ring'></View>
                    </View>
                    <View className='expert-info'>
                        <View className='expert-name'>{selectedExpert.nickname}</View>
                        <View className='expert-title-badge'>
                            <AtIcon value='sketch' size='14' color='#ffd700' />
                            <Text>{selectedExpert.title || '技术专家'}</Text>
                        </View>
                    </View>
                </View>
                
                {selectedExpert.skills && selectedExpert.skills.length > 0 && (
                    <View className='expert-skills-section'>
                        <View className='section-label'>
                            <Text className='label-text'>擅长技能</Text>
                            <View className='label-line'></View>
                        </View>
                        <View className='skills-grid'>
                            {selectedExpert.skills.map((skill, idx) => (
                                <View key={idx} className='skill-tag'>
                                    {typeof skill === 'object' && skill.icon && <Image src={skill.icon} className='skill-icon' />}
                                    <Text className='skill-text'>{typeof skill === 'object' ? skill.text : skill}</Text>
                                </View>
                            ))}
                        </View>
                    </View>
                )}
            </View>
        )}
      </AtFloatLayout>
    </View>
  )
}

export default ForumDetail
