import React, { useState, useEffect } from 'react'
import Taro, { useRouter, useShareAppMessage, useDidShow } from '@tarojs/taro'
import { View, Text, Image, Button, RichText } from '@tarojs/components'
import { AtIcon, AtProgress, AtModal, AtModalHeader, AtModalContent, AtModalAction, AtInput } from 'taro-ui'
import { getActivityDetail, signupActivity } from '../../../api'
import { marked } from 'marked'
import './detail.scss'

const ActivityDetail = () => {
  const router = useRouter()
  const { id } = router.params
  
  const [activity, setActivity] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [htmlContent, setHtmlContent] = useState('')
  const [signupPercentage, setSignupPercentage] = useState(0)

  // Signup Form State
  const [showSignupModal, setShowSignupModal] = useState(false)
  const [formData, setFormData] = useState<any>({})

  // Function to refresh data, can be used in useDidShow
  const refreshData = () => {
    if (id && id !== 'undefined' && id !== 'null' && !isNaN(Number(id))) {
        fetchDetail()
    } else {
        setLoading(false)
        setActivity(null)
    }
  }

  useDidShow(() => {
    refreshData()
  })

  useEffect(() => {
    refreshData()
  }, [id])

  const fetchDetail = async () => {
    try {
      const res = await getActivityDetail(Number(id))
      const data = res.data || res
      console.log('Activity Detail Data:', data) // Debug Log
      console.log('Current Signups:', data.current_signups) // Debug Log
      setActivity(data)
      
      // Calculate signup progress
      if (data.max_participants > 0) {
          const percent = Math.min(100, Math.round((data.current_signups || 0) / data.max_participants * 100))
          setSignupPercentage(percent)
      }

      if (data.description) {
          const html = marked.parse(data.description)
          setHtmlContent((html as string).replace(/<img/g, '<img style="max-width:100%;border-radius:8px;"'))
      }
    } catch (error) {
      console.error(error)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const handleSignup = async () => {
    const token = Taro.getStorageSync('token')
    if (!token) {
        Taro.showToast({ title: '请先登录', icon: 'none' })
        // Optional: Redirect to login
        // Taro.navigateTo({ url: '/pages/user/login' })
        return
    }

    // Check if form config exists
    if (activity.signup_form_config && activity.signup_form_config.length > 0) {
        setFormData({}) // Reset form
        setShowSignupModal(true)
        return
    }

    // Direct signup if no config
    submitSignup({})
  }

  const submitSignup = async (data: any) => {
    setSubmitting(true)
    try {
        await signupActivity(Number(id), { signup_info: data })
        Taro.showToast({ title: '报名成功', icon: 'success' })
        setShowSignupModal(false)
        fetchDetail() // Refresh status
    } catch (error: any) {
        console.error(error)
        // Request utility already handles error toasts
        if (error?.statusCode === 400) {
            // If likely already signed up, refresh to update UI
            fetchDetail()
            setShowSignupModal(false)
        }
    } finally {
        setSubmitting(false)
    }
  }

  const handleFormChange = (fieldName, value) => {
      setFormData(prev => ({
          ...prev,
          [fieldName]: value
      }))
  }

  const handleModalConfirm = () => {
      // Validate
      if (activity.signup_form_config) {
          for (const field of activity.signup_form_config) {
              if (field.required && !formData[field.name]) {
                  Taro.showToast({ title: `请填写${field.label}`, icon: 'none' })
                  return
              }
          }
      }
      submitSignup(formData)
  }

  useShareAppMessage(() => {
      return {
          title: activity?.title || '社区活动',
          path: `/subpackages/forum/activity/detail?id=${id}`
      }
  })

  if (loading) return <View className='loading-container'><Text>Loading...</Text></View>
  if (!activity) return <View className='error-container'><Text>活动不存在</Text></View>

  const isFull = activity.max_participants > 0 && (activity.current_signups || 0) >= activity.max_participants
  const isEnded = new Date(activity.end_time) < new Date()
  const canSignup = activity.is_active && !isFull && !isEnded && !activity.has_signed_up

  return (
    <View className='activity-detail-page'>
      {/* Hero Banner */}
      <View className='hero-section'>
        <Image 
            src={activity.display_banner_url || activity.banner_url || activity.cover_image || 'https://via.placeholder.com/800x600'} 
            mode='aspectFill' 
            className='hero-bg' 
        />
        <View className='hero-overlay'>
            <View className='status-tag'>
                {isEnded ? '已结束' : (isFull ? '名额已满' : '报名中')}
            </View>
            <Text className='hero-title'>{activity.title}</Text>
        </View>
      </View>

      <View className='main-content'>
        {/* Info Cards */}
        <View className='info-grid'>
            <View className='info-card time'>
                <AtIcon value='clock' size='24' color='#00f0ff' />
                <View className='info-text'>
                    <Text className='label'>开始时间</Text>
                    <Text className='value'>{new Date(activity.start_time).toLocaleString()}</Text>
                </View>
            </View>
            <View className='info-card location'>
                <AtIcon value='map-pin' size='24' color='#bd00ff' />
                <View className='info-text'>
                    <Text className='label'>活动地点</Text>
                    <Text className='value'>{activity.location || '线上直播'}</Text>
                </View>
            </View>
        </View>

        {/* Signup Stats */}
        <View className='stats-section'>
            <View className='stats-header'>
                <Text className='stats-title'>报名进度</Text>
                <Text className='stats-count'>
                    <Text className='current'>{activity.current_signups || 0}</Text>
                    <Text className='divider'>/</Text>
                    <Text className='max'>{activity.max_participants > 0 ? activity.max_participants : '∞'}</Text>
                </Text>
            </View>
            <View className='progress-bar-container'>
                <View className='progress-bar' style={{width: `${signupPercentage}%`}} />
                <View className='progress-glow' style={{left: `${signupPercentage}%`}} />
            </View>
        </View>

        {/* Detail Content */}
        <View className='detail-section'>
            <View className='section-header'>
                <Text className='title-text'>活动详情</Text>
                <View className='line' />
            </View>
            <View className='rich-text-wrapper'>
                <RichText nodes={htmlContent} />
            </View>
        </View>
      </View>

      {/* Footer Action Bar */}
      <View className='footer-action-bar'>
        <View className='left-info'>
            <Text className='price'>免费</Text>
            <Text className='desc'>限时活动</Text>
        </View>
        <Button 
            className={`action-btn ${canSignup ? 'active' : 'disabled'}`}
            disabled={!canSignup || submitting}
            onClick={handleSignup}
        >
            {submitting ? '提交中...' : (
                activity.has_signed_up ? '您已报名' : (
                    isEnded ? '活动已结束' : (
                        isFull ? '名额已满' : '立即报名'
                    )
                )
            )}
        </Button>
      </View>

      {/* Signup Form Modal */}
      <AtModal isOpened={showSignupModal} onClose={() => setShowSignupModal(false)}>
        <AtModalHeader>填写报名信息</AtModalHeader>
        <AtModalContent>
            <View className='signup-form'>
                {activity.signup_form_config && activity.signup_form_config.map((field, idx) => (
                    <AtInput
                        key={idx}
                        name={field.name}
                        title={field.label}
                        type={field.type || 'text'}
                        placeholder={`请输入${field.label}`}
                        value={formData[field.name]}
                        onChange={(val) => handleFormChange(field.name, val)}
                        required={field.required}
                    />
                ))}
            </View>
        </AtModalContent>
        <AtModalAction>
            <Button onClick={() => setShowSignupModal(false)}>取消</Button>
            <Button onClick={handleModalConfirm} style={{color: '#00b96b'}}>提交报名</Button>
        </AtModalAction>
      </AtModal>
    </View>
  )
}

export default ActivityDetail