import React, { useState, useEffect } from 'react'
import Taro, { useRouter, useShareAppMessage, useShareTimeline, useDidShow } from '@tarojs/taro'
import { View, Text, Image, Button, Picker } from '@tarojs/components'
import { AtIcon, AtModal, AtModalHeader, AtModalContent, AtModalAction, AtInput, AtTextarea, AtRadio, AtCheckbox } from 'taro-ui'
import { getActivityDetail, signupActivity } from '../../../api'
import MarkdownReader from '../../../components/MarkdownReader'
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 [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)
      }
    } 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
    }
    
    // Check if already unpaid (resume payment)
    if (activity.my_signup_status === 'unpaid' && activity.my_order_id) {
        Taro.navigateTo({ url: `/pages/order/payment?id=${activity.my_order_id}` })
        return
    }

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

  const submitSignup = async (data: any) => {
    setSubmitting(true)
    try {
        const res = await signupActivity(Number(id), { signup_info: data })
        
        // Handle payment if order_id is returned
        if (res.order_id) {
            Taro.showToast({ title: '即将跳转支付', icon: 'none' })
            setShowSignupModal(false)
            setTimeout(() => {
                Taro.navigateTo({ url: `/pages/order/payment?id=${res.order_id}` })
            }, 1500)
            return
        }

        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 && Array.isArray(activity.signup_form_config)) {
          for (const field of activity.signup_form_config) {
              // Defensive programming: skip invalid fields
              if (!field || typeof field !== 'object') continue
              
              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}`,
      imageUrl: activity?.display_banner_url || activity?.banner_url || activity?.cover_image
    }
  })

  useShareTimeline(() => {
    return {
      title: activity?.title || '社区活动',
      query: `id=${id}`,
      imageUrl: activity?.display_banner_url || activity?.banner_url || activity?.cover_image
    }
  })

  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 hasConfirmed = activity.has_signed_up
  const isPending = activity.my_signup_status === 'pending'
  const isUnpaid = activity.my_signup_status === 'unpaid'
  const isPaid = activity.is_paid

  const canSignup = activity.is_active && !isEnded && 
    (
        (!hasConfirmed && !isPending && !isUnpaid && !isFull) || 
        (isUnpaid && isPaid)
    )

  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'>
                <MarkdownReader content={activity.description} themeColor='#00f0ff' />
            </View>
        </View>
      </View>

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

      {/* Signup Form Modal */}
      <AtModal isOpened={showSignupModal} onClose={() => setShowSignupModal(false)}>
        <AtModalHeader>填写报名信息</AtModalHeader>
        <AtModalContent>
            <View className='signup-form'>
                {activity.signup_form_config && Array.isArray(activity.signup_form_config) && activity.signup_form_config.map((field, idx) => {
                    // Defensive programming: skip invalid fields or known bad data
                    if (!field || typeof field !== 'object' || field.label === '自定义报名配置') return null
                    
                    if (field.type === 'select') {
                        const currentOption = field.options?.find(opt => opt.value === formData[field.name])
                        return (
                            <View key={idx} className='form-field-wrapper'>
                                <Picker 
                                    mode='selector' 
                                    range={field.options || []} 
                                    rangeKey='label'
                                    onChange={(e) => {
                                        const index = e.detail.value
                                        const selected = field.options?.[index]
                                        if (selected) {
                                            handleFormChange(field.name, selected.value)
                                        }
                                    }}
                                >
                                    <AtInput
                                        name={field.name}
                                        title={field.label}
                                        type='text'
                                        placeholder={field.placeholder || `请选择${field.label}`}
                                        value={currentOption ? currentOption.label : ''}
                                        editable={false}
                                        required={field.required}
                                    />
                                </Picker>
                            </View>
                        )
                    }

                    if (field.type === 'radio') {
                        return (
                            <View key={idx} className='form-field-wrapper custom-field'>
                                <View className='field-label'>
                                    {field.required && <Text className='required'>*</Text>}
                                    {field.label}
                                </View>
                                <AtRadio
                                    options={field.options || []}
                                    value={formData[field.name]}
                                    onClick={(val) => handleFormChange(field.name, val)}
                                />
                            </View>
                        )
                    }

                    if (field.type === 'checkbox') {
                        return (
                            <View key={idx} className='form-field-wrapper custom-field'>
                                <View className='field-label'>
                                    {field.required && <Text className='required'>*</Text>}
                                    {field.label}
                                </View>
                                <AtCheckbox
                                    options={field.options || []}
                                    selectedList={formData[field.name] || []}
                                    onChange={(val) => handleFormChange(field.name, val)}
                                />
                            </View>
                        )
                    }

                    if (field.type === 'textarea') {
                        return (
                            <View key={idx} className='form-field-wrapper custom-field'>
                                <View className='field-label'>
                                    {field.required && <Text className='required'>*</Text>}
                                    {field.label}
                                </View>
                                <AtTextarea
                                    value={formData[field.name] || ''}
                                    onChange={(val) => handleFormChange(field.name, val)}
                                    placeholder={field.placeholder || `请输入${field.label}`}
                                    maxLength={500}
                                />
                            </View>
                        )
                    }

                    return (
                        <View key={idx} className='form-field-wrapper'>
                            <AtInput
                                name={field.name}
                                title={field.label}
                                type={field.type === 'tel' ? 'phone' : (field.type === 'number' ? 'number' : 'text')}
                                placeholder={field.placeholder || `请输入${field.label}`}
                                value={formData[field.name]}
                                onChange={(val) => handleFormChange(field.name, val)}
                                required={field.required}
                            />
                        </View>
                    )
                })}
            </View>
        </AtModalContent>
        <AtModalAction>
            <Button onClick={() => setShowSignupModal(false)}>取消</Button>
            <Button onClick={handleModalConfirm} style={{color: '#00b96b'}}>提交报名</Button>
        </AtModalAction>
      </AtModal>
    </View>
  )
}

export default ActivityDetail
