import React, { useState } from 'react'
import { View, Text,  Button, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import ActivityTypeSwitch, { type ActivityType } from '../../components/ActivityTypeSwitch'
import PublishForm from './publishForm'
import { publishBallFormSchema } from '../../config/formSchema/publishBallFormSchema';
import { PublishBallFormData } from '../../../types/publishBall';
import PublishService from '@/services/publishService';
import images from '@/config/images'
import styles from './index.module.scss'

const PublishBall: React.FC = () => {
  const [activityType, setActivityType] = useState<ActivityType>('individual')
  const [formData, setFormData] = useState<PublishBallFormData[]>([
    {
      title: '',
      timeRange: {
        startDate: '2025-11-23',
        startTime: '08:00',
        endTime: '10:00'
      },
      fee: '',
      location: '',
      gameplay: '',
      minParticipants: 1,
      maxParticipants: 4,
      ntpLevel: [2.0, 4.0],
      additionalRequirements: '',
      autoDegrade: false
    }
  ])
  
  // 删除确认弹窗状态
  const [deleteConfirm, setDeleteConfirm] = useState<{
    visible: boolean;
    index: number;
  }>({
    visible: false,
    index: -1
  })

  // 更新表单数据
  const updateFormData = (key: keyof PublishBallFormData, value: any, index: number) => {
    setFormData(prev => {
      const newData = [...prev]
      newData[index] = { ...newData[index], [key]: value }
      return newData
    })
  }



  // 处理活动类型变化
  const handleActivityTypeChange = (type: ActivityType) => {
    setActivityType(type)
  }

  const handleAdd = () => {
    setFormData(prev => [...prev, {
      title: '',
      timeRange: {
        startDate: '2025-11-23',
        startTime: '08:00',
        endTime: '10:00'
      },
      fee: '',
      location: '',
      gameplay: '',
      minParticipants: 1,
      maxParticipants: 4,
      ntpLevel: [2.0, 4.0],
      additionalRequirements: '',
      autoDegrade: false
    }])
  }

  // 复制上一场数据
  const handleCopyPrevious = (index: number) => {
    if (index > 0) {
      setFormData(prev => {
        const newData = [...prev]
        newData[index] = { ...newData[index - 1] }
        return newData
      })
      Taro.showToast({
        title: '已复制上一场数据',
        icon: 'success'
      })
    }
  }

  // 删除确认弹窗
  const showDeleteConfirm = (index: number) => {
    setDeleteConfirm({
      visible: true,
      index
    })
  }

  // 关闭删除确认弹窗
  const closeDeleteConfirm = () => {
    setDeleteConfirm({
      visible: false,
      index: -1
    })
  }

  // 确认删除
  const confirmDelete = () => {
    if (deleteConfirm.index >= 0) {
      setFormData(prev => prev.filter((_, index) => index !== deleteConfirm.index))
      closeDeleteConfirm()
      Taro.showToast({
        title: '已删除该场次',
        icon: 'success'
      })
    }
  }


  // 提交表单
  const handleSubmit = async () => {
    // 基础验证

    // TODO: 实现提交逻辑
    const res = await PublishService.createPersonal({
      "title": "周末网球约球",
      "venue_id": 1,
      "creator_id": 1,
      "game_date": "2024-06-15",
      "start_time": "14:00",
      "end_time": "16:00",
      "max_participants": 4,
      "current_participants": 2,
      "ntrp_level": "2.0-4.0",
      "play_style": "单打",
      "description": "周末约球，欢迎参加",
    })
    console.log(res);
    Taro.showToast({
      title: '发布成功',
      icon: 'success'
    })
  }

  return (
    <View className={styles['publish-ball']}>
      {/* 活动类型切换 */}
      <View className={styles['activity-type-switch']}>
        <ActivityTypeSwitch 
          value={activityType}
          onChange={handleActivityTypeChange}
        />
      </View>
      
      <View className={styles['publish-ball__scroll']}>
        {
          formData.map((item, index) => (
            <View key={index}>
              {/* 场次标题行 */}
              {activityType === 'group' && index > 0 && (
                <View className={styles['session-header']}>
                  <View className={styles['session-title']}>
                  第{index + 1}场
                  <View 
                      className={styles['session-delete']} 
                      onClick={() => showDeleteConfirm(index)}
                    >
                      <Image src={images.ICON_DELETE} className={styles['session-delete-icon']} />
                      
                    </View>
                  </View>
                  <View className={styles['session-actions']}>
                    
                    {index > 0 && (
                      <View 
                        className={styles['session-action-btn']} 
                        onClick={() => handleCopyPrevious(index)}
                      >
                        复制上一场
                      </View>
                    )}
                  </View>
                </View>
              )}
              <PublishForm 
                formData={item} 
                onChange={(key, value) => updateFormData(key, value, index)} 
                optionsConfig={publishBallFormSchema} 
              />
            </View>
          ))
        }
        {
          activityType === 'group' && (
            <View className={styles['publish-ball__add']} onClick={handleAdd}>
              <Image src={images.ICON_ADD} className={styles['publish-ball__add-icon']} />
              再添加一场
            </View>
          )
        }
      </View>

      {/* 删除确认弹窗 */}
      {deleteConfirm.visible && (
        <View className={styles['delete-modal']}>
          <View className={styles['delete-modal__content']}>
            <Text className={styles['delete-modal__title']}>确认移除该场次？</Text>
            <Text className={styles['delete-modal__desc']}>该操作不可恢复</Text>
            <View className={styles['delete-modal__actions']}>
              <Button 
                className={styles['delete-modal__btn']} 
                onClick={closeDeleteConfirm}
              >
                再想想
              </Button>
              <Button 
                className={styles['delete-modal__btn']} 
                onClick={confirmDelete}
              >
                确认移除
              </Button>
            </View>
          </View>
        </View>
      )}

      {/* 完成按钮 */}
      <View className={styles['submit-section']}>
        <Button className={styles['submit-btn']} onClick={handleSubmit}>
          发布
        </Button>
        <Text className={styles['submit-tip']}>
          点击确定发布约球，即表示已经同意条款
          <Text className={styles['link']}>《约球规则》</Text>
        </Text>
      </View>
    </View>
  )
}

export default PublishBall
