import React, { useState, useEffect } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { View, Text, Input, Textarea, Button, Picker, ScrollView, RichText } from '@tarojs/components'
import { createTopic, updateTopic, getTopicDetail, uploadMedia } from '../../../api'
import { marked } from 'marked'
import './create.scss'

const CreateTopic = () => {
  const router = useRouter()
  const { id } = router.params
  
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [categoryIndex, setCategoryIndex] = useState(0)
  const [loading, setLoading] = useState(false)
  const [isPreview, setIsPreview] = useState(false)

  const categories = [
    { key: 'discussion', label: '技术讨论' },
    { key: 'help', label: '求助问答' },
    { key: 'share', label: '经验分享' },
  ]

  useEffect(() => {
    if (id) {
        const fetchDetail = async () => {
            Taro.showLoading({ title: '加载中...' })
            try {
                const res = await getTopicDetail(Number(id))
                const topic = res.data || res
                setTitle(topic.title)
                setContent(topic.content)
                const idx = categories.findIndex(c => c.key === topic.category)
                if (idx !== -1) setCategoryIndex(idx)
                
                Taro.setNavigationBarTitle({ title: '编辑话题' })
            } catch (error) {
                console.error(error)
                Taro.showToast({ title: '加载失败', icon: 'none' })
            } finally {
                Taro.hideLoading()
            }
        }
        fetchDetail()
    }
  }, [id])

  const handleCategoryChange = (e) => {
    setCategoryIndex(e.detail.value)
  }

  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
          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`
              
          setContent(prev => prev + insertText)
          
          Taro.hideLoading()
      } catch (error) {
          console.error(error)
          Taro.hideLoading()
          // Only toast if it's an error, not cancel
          if (error.errMsg && error.errMsg.indexOf('cancel') === -1) {
              Taro.showToast({ title: '上传失败', icon: 'none' })
          }
      }
  }

  const handleSubmit = async () => {
    if (!title.trim() || !content.trim()) {
      Taro.showToast({ title: '请填写完整', icon: 'none' })
      return
    }

    setLoading(true)
    try {
      if (id) {
          await updateTopic(Number(id), {
              title,
              content,
              category: categories[categoryIndex].key
          })
          Taro.showToast({ title: '更新成功', icon: 'success' })
      } else {
          await createTopic({
            title,
            content,
            category: categories[categoryIndex].key
          })
          Taro.showToast({ title: '发布成功', icon: 'success' })
      }
      
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    } catch (error) {
      console.error(error)
      Taro.showToast({ title: id ? '更新失败' : '发布失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  return (
    <ScrollView scrollY className='create-topic-page'>
      <View className='content-wrapper'>
        <View className='header-actions'>
            <View 
                className={`action-item ${!isPreview ? 'active' : ''}`} 
                onClick={() => setIsPreview(false)}
            >
                编辑
            </View>
            <View 
                className={`action-item ${isPreview ? 'active' : ''}`} 
                onClick={() => setIsPreview(true)}
            >
                预览
            </View>
        </View>

        {!isPreview ? (
            <>
                <View className='form-item'>
                    <Text className='label'>板块</Text>
                    <Picker range={categories} rangeKey='label' value={categoryIndex} onChange={handleCategoryChange}>
                    <View className='picker'>
                        {categories[categoryIndex].label}
                    </View>
                    </Picker>
                </View>

                <View className='form-item'>
                    <Text className='label'>标题</Text>
                    <Input 
                    value={title}
                    onInput={e => setTitle(e.detail.value)}
                    placeholder='请输入标题' 
                    />
                </View>

                <View className='form-item'>
                    <Text className='label'>内容 (支持 Markdown)</Text>
                    <Textarea 
                    value={content}
                    onInput={e => setContent(e.detail.value)}
                    placeholder='分享你的想法...'
                    maxlength={-1}
                    />
                </View>
                
                <View className='media-upload'>
                    <View className='upload-btn' onClick={handleUpload}>
                        + 插入图片/视频
                    </View>
                </View>
            </>
        ) : (
            <View className='preview-container'>
                <View className='preview-title'>{title || '无标题'}</View>
                <View className='markdown-body'>
                    <RichText nodes={(marked.parse(content || '无内容') as string).replace(/<img/g, '<img style="max-width:100%;border-radius:8px;"')} />
                </View>
            </View>
        )}

        <Button 
            className={`submit-btn ${loading ? 'disabled' : ''}`}
            onClick={handleSubmit}
            disabled={loading}
        >
            {loading ? (id ? '更新中...' : '发布中...') : (id ? '更新话题' : '发布话题')}
        </Button>
      </View>
    </ScrollView>
  )
}

export default CreateTopic
