import React, { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Button, Image, ScrollView } from '@tarojs/components';
import { useRoom } from '../../../contexts/RoomContext';
import { useUser } from '../../../contexts/UserContext';
import { turtleSoupService } from '../../../services/api';
import { FaCrown, FaGem, FaBook } from 'react-icons/fa';
import './index.scss';

export default function TurtleSoupHost() {
  const { user } = useUser();
  const { currentRoom, updateGameData, startGame, isLoading } = useRoom();
  
  const [riddles, setRiddles] = useState<any[]>([]);
  const [selectedRiddleId, setSelectedRiddleId] = useState<string>('');
  const [questions, setQuestions] = useState<any[]>([]);
  const [answerContent, setAnswerContent] = useState<string>('');
  const [clueContent, setClueContent] = useState<string>('');
  const [isRevealed, setIsRevealed] = useState<boolean>(false);
  const [hasGameStarted, setHasGameStarted] = useState<boolean>(false);
  const [loadingRiddles, setLoadingRiddles] = useState<boolean>(false);
  
  // 付费内容相关状态
  const [hasPremiumRiddles, setHasPremiumRiddles] = useState<boolean>(false);
  const [showPremiumModal, setShowPremiumModal] = useState<boolean>(false);
  const [premiumRiddles, setPremiumRiddles] = useState<any[]>([]);

  // 模拟初始化获取谜题
  useEffect(() => {
    fetchRiddles();
  }, []);

  // 监听游戏状态变化
  useEffect(() => {
    if (currentRoom?.gameData?.questions) {
      setQuestions(currentRoom.gameData.questions);
    }
    
    if (currentRoom?.gameData?.hostRevealedAnswer) {
      setIsRevealed(true);
    }
    
    if (currentRoom?.status === 'playing' && currentRoom.gameData) {
      setHasGameStarted(true);
    }
  }, [currentRoom]);

  // 获取普通谜题
  const fetchRiddles = async () => {
    setLoadingRiddles(true);
    try {
      // 模拟普通谜题数据
      const mockRiddles = [
        { _id: 'r1', title: '奇怪的旅馆', difficulty: 'medium', isPremium: false },
        { _id: 'r2', title: '回家的路', difficulty: 'hard', isPremium: false },
        { _id: 'r3', title: '沙漠中的点', difficulty: 'medium', isPremium: false },
        { _id: 'r4', title: '最后的晚餐', difficulty: 'easy', isPremium: false },
      ];
      
      // 设置一些高级谜题
      const mockPremiumRiddles = [
        { _id: 'pr1', title: '神秘的照片', difficulty: 'hard', isPremium: true },
        { _id: 'pr2', title: '消失的行李', difficulty: 'medium', isPremium: true },
        { _id: 'pr3', title: '古老的信件', difficulty: 'expert', isPremium: true },
      ];
      
      setRiddles(mockRiddles);
      setPremiumRiddles(mockPremiumRiddles);
    } catch (error) {
      console.error('获取谜题失败:', error);
      Taro.showToast({
        title: '获取谜题失败',
        icon: 'none'
      });
    } finally {
      setLoadingRiddles(false);
    }
  };

  // 选择谜题
  const handleSelectRiddle = (riddleId: string) => {
    setSelectedRiddleId(riddleId);
  };

  // 初始化游戏
  const handleInitGame = async () => {
    if (!selectedRiddleId) {
      Taro.showToast({
        title: '请先选择一个谜题',
        icon: 'none'
      });
      return;
    }

    if (!currentRoom?.roomId) {
      Taro.showToast({
        title: '房间信息获取失败',
        icon: 'none'
      });
      return;
    }

    Taro.showLoading({ title: '初始化游戏中...' });
    try {
      const res = await turtleSoupService.initGameData(currentRoom.roomId, selectedRiddleId);
      if (res.code === 200) {
        await startGame();
        setHasGameStarted(true);
        Taro.showToast({
          title: '游戏初始化成功',
          icon: 'success'
        });
      } else {
        Taro.showToast({
          title: res.message || '初始化游戏失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('初始化游戏失败:', error);
      Taro.showToast({
        title: '初始化游戏失败',
        icon: 'none'
      });
    } finally {
      Taro.hideLoading();
    }
  };

  // 回答问题
  const handleAnswerQuestion = async (questionId: string, status: 'answered' | 'rejected') => {
    if (!answerContent && status === 'answered') {
      Taro.showToast({
        title: '请输入回答内容',
        icon: 'none'
      });
      return;
    }

    Taro.showLoading({ title: '提交中...' });
    try {
      const res = await turtleSoupService.answerQuestion(
        currentRoom!.roomId,
        questionId,
        answerContent,
        status
      );
      if (res.code === 200) {
        setAnswerContent('');
        Taro.showToast({
          title: '回答成功',
          icon: 'success'
        });
      } else {
        Taro.showToast({
          title: res.message || '回答失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('回答问题失败:', error);
      Taro.showToast({
        title: '回答问题失败',
        icon: 'none'
      });
    } finally {
      Taro.hideLoading();
    }
  };

  // 提交线索
  const handleSubmitClue = async () => {
    if (!clueContent) {
      Taro.showToast({
        title: '请输入线索内容',
        icon: 'none'
      });
      return;
    }

    Taro.showLoading({ title: '提交中...' });
    try {
      const res = await turtleSoupService.submitClue(currentRoom!.roomId, clueContent);
      if (res.code === 200) {
        setClueContent('');
        Taro.showToast({
          title: '线索提交成功',
          icon: 'success'
        });
      } else {
        Taro.showToast({
          title: res.message || '线索提交失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('提交线索失败:', error);
      Taro.showToast({
        title: '提交线索失败',
        icon: 'none'
      });
    } finally {
      Taro.hideLoading();
    }
  };

  // 揭晓答案
  const handleRevealAnswer = async () => {
    Taro.showModal({
      title: '确认揭晓答案',
      content: '揭晓答案后游戏将结束，确定要揭晓吗？',
      success: async (res) => {
        if (res.confirm) {
          Taro.showLoading({ title: '处理中...' });
          try {
            const res = await turtleSoupService.revealAnswer(currentRoom!.roomId);
            if (res.code === 200) {
              setIsRevealed(true);
              Taro.showToast({
                title: '已揭晓答案',
                icon: 'success'
              });
            } else {
              Taro.showToast({
                title: res.message || '揭晓答案失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('揭晓答案失败:', error);
            Taro.showToast({
              title: '揭晓答案失败',
              icon: 'none'
            });
          } finally {
            Taro.hideLoading();
          }
        }
      }
    });
  };

  // 支付购买高级主题 (1小时)
  const handleBuyPremiumRiddles = () => {
    Taro.showModal({
      title: '购买高级主题',
      content: '解锁所有高级主题，有效期1小时，价格1元。',
      confirmText: '立即购买',
      success: (res) => {
        if (res.confirm) {
          // 调用微信支付API
          Taro.requestPayment({
            timeStamp: String(Date.now()),
            nonceStr: 'nonceStr',
            package: 'prepay_id=wx123456789abcdef',
            signType: 'MD5',
            paySign: 'paySign',
            success: () => {
              setHasPremiumRiddles(true);
              setShowPremiumModal(false);
              Taro.showToast({
                title: '购买成功，已解锁高级主题',
                icon: 'success'
              });
              
              // 生产环境应该有服务端验证和处理
              // 启动计时器，1小时后失效
              setTimeout(() => {
                setHasPremiumRiddles(false);
                Taro.showToast({
                  title: '高级主题已到期',
                  icon: 'none'
                });
              }, 3600000); // 1小时
            },
            fail: () => {
              Taro.showToast({
                title: '支付失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  };

  // 房间未启动页面
  if (!hasGameStarted) {
    return (
      <View className='host-waiting-room'>
        <View className='room-info'>
          <Text className='room-code'>房间号: {currentRoom?.roomCode}</Text>
          <Text className='player-count'>玩家: {currentRoom?.players.filter(p => p.status === 'active').length} / {currentRoom?.maxPlayers}</Text>
        </View>
        
        <View className='riddle-selection'>
          <View className='selection-header'>
            <Text className='title'>选择谜题</Text>
            {!hasPremiumRiddles && (
              <Button 
                className='premium-button' 
                size='mini' 
                onClick={() => setShowPremiumModal(true)}
              >
                解锁高级主题
              </Button>
            )}
          </View>
          
          {loadingRiddles ? (
            <View className='loading'>加载中...</View>
          ) : (
            <ScrollView scrollY className='riddle-list'>
              {riddles.map(riddle => (
                <View 
                  key={riddle._id}
                  className={`riddle-item ${selectedRiddleId === riddle._id ? 'selected' : ''}`}
                  onClick={() => handleSelectRiddle(riddle._id)}
                >
                  <Text className='riddle-title'>{riddle.title}</Text>
                  <Text className={`difficulty ${riddle.difficulty}`}>{riddle.difficulty}</Text>
                </View>
              ))}
              
              {hasPremiumRiddles && premiumRiddles.map(riddle => (
                <View 
                  key={riddle._id}
                  className={`riddle-item premium ${selectedRiddleId === riddle._id ? 'selected' : ''}`}
                  onClick={() => handleSelectRiddle(riddle._id)}
                >
                  <Text className='riddle-title'>{riddle.title}</Text>
                  <Text className={`difficulty ${riddle.difficulty}`}>{riddle.difficulty}</Text>
                  <View className='premium-icon'>
                    <FaCrown size={16} color="#ffc107" />
                  </View>
                </View>
              ))}
            </ScrollView>
          )}
        </View>
        
        <Button 
          className='start-button' 
          loading={isLoading} 
          disabled={!selectedRiddleId || isLoading}
          onClick={handleInitGame}
        >
          开始游戏
        </Button>
        
        {/* 高级主题购买弹窗 */}
        {showPremiumModal && (
          <View className='premium-modal'>
            <View className='modal-content'>
              <View className='modal-header'>
                <Text className='modal-title'>解锁高级主题</Text>
              </View>
              <View className='modal-body'>
                <Text className='modal-description'>
                  解锁后可使用全部高级谜题，更具挑战性和精彩性，有效期1小时。
                </Text>
                <View className='premium-features'>
                  <View className='feature-item'>
                    <View className='feature-icon'>
                      <FaGem size={24} color="#ffc107" />
                    </View>
                    <Text className='feature-text'>专属高难度谜题</Text>
                  </View>
                  <View className='feature-item'>
                    <View className='feature-icon'>
                      <FaBook size={24} color="#52c41a" />
                    </View>
                    <Text className='feature-text'>精心设计的故事线</Text>
                  </View>
                </View>
                <Text className='price'>¥1.00 / 1小时</Text>
              </View>
              <View className='modal-footer'>
                <Button className='cancel-button' onClick={() => setShowPremiumModal(false)}>取消</Button>
                <Button className='confirm-button' onClick={handleBuyPremiumRiddles}>立即购买</Button>
              </View>
            </View>
          </View>
        )}
      </View>
    );
  }

  // 游戏已启动页面
  return (
    <View className='host-game-view'>
      <View className='game-header'>
        <Text className='title'>{currentRoom?.gameData?.title || '海龟汤游戏'}</Text>
        <Text className='room-code'>房间号: {currentRoom?.roomCode}</Text>
      </View>
      
      <View className='game-description'>
        <Text className='label'>题目描述:</Text>
        <Text className='content'>{currentRoom?.gameData?.description}</Text>
      </View>
      
      {isRevealed && (
        <View className='game-answer'>
          <Text className='label'>答案揭晓:</Text>
          <Text className='content'>{currentRoom?.gameData?.answer}</Text>
        </View>
      )}
      
      <View className='questions-section'>
        <Text className='section-title'>玩家提问</Text>
        <ScrollView scrollY className='questions-list'>
          {questions.length > 0 ? (
            questions.map(question => (
              <View key={question.id} className='question-item'>
                <View className='question-header'>
                  <Text className='player-name'>{question.askedBy.nickName}:</Text>
                  <Text className={`status ${question.status}`}>
                    {question.status === 'pending' ? '待回答' : 
                     question.status === 'answered' ? '已回答' : '已拒绝'}
                  </Text>
                </View>
                <Text className='question-content'>{question.content}</Text>
                
                {question.status === 'pending' ? (
                  <View className='answer-actions'>
                    <View className='input-wrapper'>
                      <input 
                        className='answer-input' 
                        placeholder='输入回答内容' 
                        value={answerContent}
                        onChange={e => setAnswerContent(e.target.value)}
                      />
                    </View>
                    <Button 
                      className='answer-button' 
                      size='mini'
                      onClick={() => handleAnswerQuestion(question.id, 'answered')}
                    >
                      回答
                    </Button>
                    <Button 
                      className='reject-button' 
                      size='mini'
                      onClick={() => handleAnswerQuestion(question.id, 'rejected')}
                    >
                      拒绝
                    </Button>
                  </View>
                ) : (
                  question.status === 'answered' && (
                    <View className='answer-display'>
                      <Text className='answer-label'>回答:</Text>
                      <Text className='answer-content'>{question.answer}</Text>
                    </View>
                  )
                )}
              </View>
            ))
          ) : (
            <View className='empty-state'>暂无玩家提问</View>
          )}
        </ScrollView>
      </View>
      
      <View className='clue-section'>
        <Text className='section-title'>提供线索</Text>
        <View className='input-wrapper'>
          <textarea
            className='clue-textarea'
            placeholder='输入线索内容...'
            value={clueContent}
            onChange={e => setClueContent(e.target.value)}
          />
        </View>
        <Button 
          className='submit-clue-button'
          disabled={!clueContent}
          onClick={handleSubmitClue}
        >
          提交线索
        </Button>
      </View>
      
      {!isRevealed && (
        <Button 
          className='reveal-answer-button'
          onClick={handleRevealAnswer}
        >
          揭晓答案
        </Button>
      )}
    </View>
  );
} 