import React from 'react';
import { useDebounceFn } from 'ahooks';
import { useActivity } from '../context/ActivityContext';
import { MissionItemViewProps } from '../types';
import { toast } from './toast'

// 需要外部自定义处理的任务类型
const CUSTOM_TASK_TYPES = [29, 30];

const MissionItemView = ({
  activityInfo,
  mission,
  onProgressUpdate,
  onCustomShare,
  onCustomTask,
  className = 'mission-item-card',
  style,
  cardClassName = 'mission-content',
  titleClassName = 'mission-title',
  rewardClassName = 'mission-reward',
  actionClassName = 'mission-action',
  buttonClassName = 'action-button',
  completedText = '已完成',
  defaultActionText = '开始任务'
}: MissionItemViewProps): React.ReactElement => {
  const { missionApi, updateMissionProgress, refreshActivity, userInfo } = useActivity();
  console.log('activityInfo-mission', activityInfo);

  // 使用 ahooks 的 useDebounceFn 实现防抖
  const { run: debouncedMissionAction } = useDebounceFn(
    async () => {
      // 未开始，则不进行领取
      if (activityInfo?.missionActivity.isNotStarted()) {
        toast('活动未开始');
        return;
      }
      // 已结束，则不进行领取
      if (activityInfo?.missionActivity.isEnded()) {
        toast('活动已结束');
        return;
      }
      if (!missionApi) return;

      try {
        console.log('mission');
        if (mission.status === 0) {
          // 领取任务奖励
          if (mission.receiveAward && typeof mission.receiveAward === 'function') {
            const result = await mission.receiveAward();
            console.log('奖励领取结果:', result);

            // 检查结果并刷新数据
            if (result && result.data.code === 200) {
              console.log('奖励领取成功，刷新活动数据');
              toast('领取成功')
              // 刷新整个活动数据 - 使用静默刷新，并获取最新数据
              const refreshResult = await refreshActivity(true);
              console.log('最新userInfo', refreshResult.userInfo?.points)
              onProgressUpdate?.(mission, refreshResult.userInfo?.points);
            } else {
              toast(result.data.msg)
            }
          } else {
            console.warn('任务对象不支持 receiveAward 方法');
          }
          return;
        }

        // 检查 showMissionType 是否为 2，如果是则执行 onCustomShare
        if (mission.info.showMissionType === 2 && onCustomShare) {
          onCustomShare(mission);
          const result = await mission.executeTask();
          // 检查结果并刷新数据
          if (result && result.needRefresh) {
            console.log('任务执行成功，刷新活动数据');
            // Todo 需要根据任务类型刷新不同的数据 比如口令邀请任务 不需要刷新
            // 刷新整个活动数据
            const refreshResult = await refreshActivity(true);
            console.log('最新userInfo', refreshResult.userInfo?.points)
            onProgressUpdate?.(mission, refreshResult.userInfo?.points);
          } else {
            // 只有在不需要刷新时才手动更新状态
            updateMissionProgress(mission);
            onProgressUpdate?.(mission, userInfo.points);
          }
          return;
        }

        // 现在 mission 是 MissionItem 实例，可以直接调用 executeTask 方法
        if (mission.executeTask && typeof mission.executeTask === 'function') {
          // 只有未完成需要执行任务
          if (mission.status === -1) {
            const showMissionType = mission.info.showMissionType;
            const isCustomTaskType = CUSTOM_TASK_TYPES.includes(showMissionType);
            
            // 对于需要自定义处理的任务类型（29、30等），使用外部传入的处理函数
            let result;
            if (isCustomTaskType && onCustomTask && mission.context) {
              console.log(`任务类型 ${showMissionType} 使用自定义处理函数`);
              result = await onCustomTask(mission.context, showMissionType, mission);
            } else if (isCustomTaskType && !onCustomTask) {
              console.warn(`任务类型 ${showMissionType} 需要自定义处理函数，但未提供 onCustomTask`);
              return;
            } else {
              result = await mission.executeTask();
            }
            console.log('任务执行结果:', result);

            // 检查结果并刷新数据
            if (result && result.needRefresh) {
              console.log('任务执行成功，刷新活动数据');
              // Todo 需要根据任务类型刷新不同的数据 比如口令邀请任务 不需要刷新
              // 刷新整个活动数据
              const refreshResult = await refreshActivity(true);
              console.log('最新userInfo', refreshResult.userInfo?.points)
              onProgressUpdate?.(mission, refreshResult.userInfo?.points);
            } else {
              // 只有在不需要刷新时才手动更新状态
              updateMissionProgress(mission);
              onProgressUpdate?.(mission, userInfo.points);
            }
          }
        } else {
          console.warn('任务对象不支持 executeTask 方法');
        }
      } catch (error) {
        console.error('任务执行失败:', error);
      }
    },
    {
      wait: 500, // 500ms 防抖延迟
    }
  );

  const handleMissionAction = () => {
    debouncedMissionAction();
  };

  const isCompleted = mission.status === 1; // MissionItem 的 status 是数字类型
  console.log('mission', mission.info.awardIcon);
  // 获取任务名称和进度文本
  const getMissionName = () => {
    return mission.info.title;
  };

  const getProgressText = () => {
    if (mission.progressText) {
      return `( ${mission.progressText} )`;
    }
    if (mission.info.currentProgress !== undefined && mission.info.totalProgress !== undefined) {
      return `( ${mission.info.currentProgress}/${mission.info.totalProgress} )`;
    }
    return '';
  };

  const computedButtonText = () => {
    console.log('activityInfo', activityInfo);
    // 未开始，则不进行领取
    if (activityInfo?.missionActivity.isNotStarted()) {
      return '未开始';
    }
    // 已结束，则不进行领取
    if (activityInfo?.missionActivity.isEnded()) {
      return '已结束';
    }
    let isCompleted = mission.status === 1; // MissionItem 的 status 是数字类型
    if (isCompleted) return completedText;
    if (mission.status === 0) {
      return '领取'
    }
    if (mission.status === 1) {
      return '已完成'
    }
    return mission.info.actionCopyWriting || defaultActionText;
  }

  const getRewardInfo = () => {
    const rewardNum = mission.info.awardNum || 5;
    const rewardName = mission.info.awardName || '积分';
    return { num: rewardNum, name: rewardName };
  };

  const reward = getRewardInfo();
  const computedRewardProgressText = () => {
    /**
     * 计算是否展示次 或者几次
     */
    if (mission.info.totalProgress > 1 && (
      mission.info.canGetAwardConditionTimes === 1
    )) {
      return '/次'
    }
    if (
      mission.info.totalProgress > 1
      && (
        mission.info.canGetAwardConditionTimes > 1
        && mission.info.showMissionType !== 28
      )
    ) {
      return `/${mission.info.canGetAwardConditionTimes}次`
    }
    return ''
  }

  return (
    <div className={className} style={style}>
      <div className={cardClassName}>
        <div className="mission-info">
          <span className={titleClassName}>
            {getMissionName()}{getProgressText()}
          </span>
          {
            mission.info.showMissionType === 27 && (
              <span className="mission-invited-avatar-list">
                {mission.info.invitedAvatarList?.map(item => (
                  <img className="mission-invited-avatar-item" src={item} alt="邀请头像" />
                ))}
              </span>
            )
          }
        </div>

        <div className={rewardClassName}>
          <div className="reward-icon">
            <img src={mission.info.awardIcon || '/default-coin.png'} alt="奖励图标" />
          </div>
          <span className="reward-amount">
            {reward.num}
            {computedRewardProgressText()}
          </span>
        </div>

        <div className={actionClassName}>
          <button
            className={`${buttonClassName} ${(isCompleted || activityInfo?.missionActivity.isNotStarted() || activityInfo?.missionActivity.isEnded()) ? 'completed' : ''}`}
            onClick={handleMissionAction}
            disabled={isCompleted || activityInfo?.missionActivity.isNotStarted() || activityInfo?.missionActivity.isEnded()}
          >
            {computedButtonText()}
          </button>
        </div>
      </div>
    </div>
  );
};

export default MissionItemView; 