import React from 'react';
import { useActivity } from '../context/ActivityContext';
import { AwardItemViewProps } from '../types';
import { toast } from './toast';

// 独立的奖品项组件（不依赖 context）
const StandaloneAwardItemView = ({
  activityInfo,
  prize,
  customRedeem,
  className = 'award-item-card',
  style,
  cardClassName = 'award-content',
  imageClassName = 'award-image',
  titleClassName = 'award-title',
  buttonClassName = 'award-button',
  redeemText = '立即兑换'
}: AwardItemViewProps): React.ReactElement => {
  // 封装兑换函数（不依赖 context）
  const redeemPrize = async (prizeCode: string, otherParams?: any): Promise<any> => {
    if (!activityInfo?.awardActivity) {
      throw new Error('奖励活动信息不可用');
    }

    const awardActivity = activityInfo.awardActivity;

    try {
      // 调用 AwardActivity 的 convertPrize 方法
      // 如果活动未开始，则不进行兑换
      if (awardActivity.isNotStarted()) {
        toast('活动未开始');
        return;
      }
      // 活动结束，则不进行兑换
      if (awardActivity.isEnded()) {
        toast('活动已结束');
        return;
      }
      console.log('开始兑换奖品:', prizeCode, otherParams);
      const result = await awardActivity.convertPrize({
        prizeCode: prizeCode,
        prizeActivityCode: awardActivity.activityCode,
        ...otherParams
      });
      console.log('兑换结果:', result)
      if (result.data.code === 200) {
        toast(result.data.data.displayMsg)
      } else {
        toast(result.data.msg)
      }
      return result
    } catch (error) {
      console.error('兑换失败:', error);
      toast('兑换失败，请重试');
      throw error;
    }
  };

  const defaultRedeem = async (prize, otherParams?: any) => {
    const result = await redeemPrize(prize.itemCode, otherParams);
    console.log('result', result)
    if (result.data.code === 200) {
      toast(result.data.data.displayMsg)
      return {
        status: true,
        points: activityInfo?.userInfo?.points // 使用传入的用户信息
      }
    } else {
      console.log('兑换失败', result.data.msg)
      toast(result.data.msg)
      return {
        status: false,
      }
    }
  }

  const handleRedeem = async () => {
    if (prize.userStatus !== 0) return;

    try {
      console.log('开始兑换奖品:', prize);
      if (customRedeem) {
        customRedeem(prize, (
          otherParams?: any
        ) => defaultRedeem(prize, otherParams))
      } else {
        await defaultRedeem(prize)
      }
    } catch (error) {
      console.error('兑换失败:', error);
    }
  };

  // 获取按钮文本和样式
  const getButtonInfo = () => {
    if (prize.userStatus === -2) {
      return { text: '已兑换', className: 'unavailable' };
    }
    if (prize.userStatus === -1) {
      return { text: '抢光了', className: 'unavailable' };
    }
    if (activityInfo?.awardActivity.isNotStarted()) {
      return { text: '未开始', className: 'unavailable' };
    }
    if (activityInfo?.awardActivity.isEnded()) {
      return { text: '已结束', className: 'unavailable' };
    }

    const costInfo = getCostInfo();
    if (costInfo) {
      return {
        text: `${costInfo.amount}积分兑换`,
        className: 'available'
      };
    }

    return { text: redeemText, className: 'available' };
  };

  // 获取消费信息
  const getCostInfo = () => {
    if (prize.prizeBizConfigDTO?.consumables) {
      const { prizeNum, prizeName } = prize.prizeBizConfigDTO.consumables;
      return { amount: prizeNum, name: prizeName };
    }
    return null;
  };

  const buttonInfo = getButtonInfo();

  return (
    <div className={className} style={style}>
      <div className={cardClassName}>
        {/* 奖品图片 */}
        <div className={imageClassName}>
          <img src={prize.image || '/default-prize.png'} alt={prize.name} />
        </div>

        {/* 奖品名称 */}
        <h3 className={titleClassName}>{prize.name}</h3>

        {/* 兑换按钮 */}
        <button
          className={`${buttonClassName} ${buttonInfo.className}`}
          onClick={handleRedeem}
        >
          {buttonInfo.text}
        </button>
      </div>
    </div>
  );
};

// 依赖 context 的奖品项组件
const ContextAwardItemView = ({
  customRedeem,
  prize,
  className = 'award-item-card',
  style,
  cardClassName = 'award-content',
  imageClassName = 'award-image',
  titleClassName = 'award-title',
  buttonClassName = 'award-button',
  redeemText = '立即兑换'
}: Omit<AwardItemViewProps, 'activityInfo'>): React.ReactElement => {
  const {
    missionApi,
    activityInfo: contextActivityInfo,
    refreshActivity
  } = useActivity();

  // 封装兑换函数
  const redeemPrize = async (
    prizeCode: string,
    otherParams?: any
  ): Promise<any> => {
    if (!contextActivityInfo?.awardActivity) {
      throw new Error('奖励活动信息不可用');
    }

    const awardActivity = contextActivityInfo.awardActivity;

    try {
      if (awardActivity.isNotStarted()) {
        toast('活动未开始');
        return;
      }
      // 活动结束，则不进行兑换
      if (awardActivity.isEnded()) {
        toast('活动已结束');
        return;
      }
      console.log('开始兑换奖品:', prizeCode, otherParams);
      const result = await awardActivity.convertPrize({
        prizeCode: prizeCode,
        prizeActivityCode: awardActivity.activityCode,
        ...otherParams
      });
      console.log('兑换结果:', result)
      if (result.data.code === 200) {
        toast(result.data.data.displayMsg)
        refreshActivity(true);
      } else {
        toast(result.data.msg)
      }
      return result
    } catch (error) {
      console.error('兑换失败:', error);
      toast('兑换失败，请重试');
      throw error;
    }
  };

  const defaultRedeem = async (
    prize,
    otherParams?: any
  ) => {
    const result = await redeemPrize(
      prize.itemCode,
      otherParams
    );
    console.log('result', result)
    if (result.data.code === 200) {
      toast(result.data.data.displayMsg)
      const latestUserInfo = await missionApi.getUserInfo();
      console.log('最新userInfo', latestUserInfo.points);
      return {
        status: true,
        points: latestUserInfo.points
      }
    } else {
      console.log('兑换失败', result.data.msg)
      toast(result.data.msg)
      return {
        status: false,
      }
    }
  }

  const handleRedeem = async () => {
    if (!missionApi || prize.userStatus !== 0) return;

    try {
      console.log('开始兑换奖品:', prize);
      if (customRedeem) {
        customRedeem(prize, (
          otherParams?: any
        ) => defaultRedeem(prize, otherParams))
      } else {
        await defaultRedeem(prize)
      }
    } catch (error) {
      console.error('兑换失败:', error);
    }
  };

  // 获取按钮文本和样式
  const getButtonInfo = () => {
    if (contextActivityInfo?.awardActivity.isNotStarted()) {
      return { text: '未开始', className: 'unavailable' };
    }
    if (contextActivityInfo?.awardActivity.isEnded()) {
      return { text: '已结束', className: 'unavailable' };
    }
    if (prize.userStatus === -2) {
      return { text: '已兑换', className: 'unavailable' };
    }
    if (prize.userStatus === -1) {
      return { text: '抢光了', className: 'unavailable' };
    }

    const costInfo = getCostInfo();
    if (costInfo) {
      return {
        text: `${costInfo.amount}积分兑换`,
        className: 'available'
      };
    }

    return { text: redeemText, className: 'available' };
  };

  // 获取消费信息
  const getCostInfo = () => {
    if (prize.prizeBizConfigDTO?.consumables) {
      const { prizeNum, prizeName } = prize.prizeBizConfigDTO.consumables;
      return { amount: prizeNum, name: prizeName };
    }
    return null;
  };

  const buttonInfo = getButtonInfo();

  return (
    <div className={className} style={style}>
      <div className={cardClassName}>
        {/* 奖品图片 */}
        <div className={imageClassName}>
          <img src={prize.image || '/default-prize.png'} alt={prize.name} />
        </div>

        {/* 奖品名称 */}
        <h3 className={titleClassName}>{prize.name}</h3>

        {/* 兑换按钮 */}
        <button
          className={`${buttonClassName} ${buttonInfo.className}`}
          onClick={handleRedeem}
        >
          {buttonInfo.text}
        </button>
      </div>
    </div>
  );
};

// 主组件：根据是否有 activityInfo 选择使用哪个子组件
const AwardItemView = (props: AwardItemViewProps): React.ReactElement => {
  // 如果传入了 activityInfo，使用独立组件（不会触发 useActivity）
  if (props.activityInfo) {
    return <StandaloneAwardItemView {...props} />;
  }

  // 否则使用依赖 context 的组件
  return <ContextAwardItemView {...props} />;
};

export default AwardItemView; 