import React, { useState, useEffect } from 'react';
import Taro, { useRouter } from '@tarojs/taro';
import { View, Text, ScrollView, Textarea } from '@tarojs/components';
import { FaUsers, FaSignOutAlt, FaPaperPlane, FaInfoCircle, FaQuestion } from 'react-icons/fa';
import Button from '../../../../components/base/Button';
import PlayerAvatar from '../../../../components/room/PlayerAvatar';
import { getRoomInfo, leaveRoom } from '../../../../services/api';
import { Room } from '../../../../interfaces';
import { PlayerRole, GameStatus, RoomStatus } from '../../../../constants';
import { TurtleSoupGameService } from '../../../../services/game';
import './index.scss';

const TurtleSoupPlayer: React.FC = () => {
  const router = useRouter();
  const { roomId, roomCode } = router.params;
  const [room, setRoom] = useState<Room | null>(null);
  const [gameData, setGameData] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isActionLoading, setIsActionLoading] = useState(false);
  const [answer, setAnswer] = useState<string>('');
  const [hasSubmitted, setHasSubmitted] = useState<boolean>(false);

  // 获取房间信息
  useEffect(() => {
    if (roomId) {
      fetchRoomInfo();
      // 设置定时刷新
      const timer = setInterval(fetchRoomInfo, 5000);
      return () => clearInterval(timer);
    }
  }, [roomId]);

  // 获取房间信息
  const fetchRoomInfo = async () => {
    try {
      if (!roomId) return;
      
      setIsLoading(true);
      const roomData = await getRoomInfo(roomId);
      setRoom(roomData);
      
      // 处理游戏数据
      if (roomData.gameId === 'turtle-soup') {
        const playerViewData = TurtleSoupGameService.getPlayerViewData(roomData);
        setGameData(playerViewData);
        
        // 检查用户是否已提交答案
        const currentUserId = await getCurrentUserId();
        if (currentUserId && playerViewData.playerAnswers && playerViewData.playerAnswers[currentUserId]) {
          setHasSubmitted(true);
        }
      }
    } catch (error) {
      console.error('获取房间信息失败:', error);
      Taro.showToast({
        title: '获取房间信息失败',
        icon: 'none',
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 获取当前用户ID
  const getCurrentUserId = async (): Promise<string | null> => {
    try {
      const userInfo = await Taro.getStorageSync('user_info');
      if (userInfo) {
        const user = JSON.parse(userInfo);
        return user.userId;
      }
      return null;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return null;
    }
  };

  // 处理答案变化
  const handleAnswerChange = (e) => {
    setAnswer(e.detail.value);
  };

  // 提交答案
  const handleSubmitAnswer = async () => {
    if (!roomId || !answer.trim()) {
      Taro.showToast({
        title: '请输入您的答案',
        icon: 'none',
      });
      return;
    }
    
    try {
      setIsActionLoading(true);
      await TurtleSoupGameService.submitAnswer(roomId, answer.trim());
      setHasSubmitted(true);
      await fetchRoomInfo();
      
      Taro.showToast({
        title: '答案已提交',
        icon: 'success',
      });
    } catch (error) {
      console.error('提交答案失败:', error);
      Taro.showToast({
        title: '提交答案失败',
        icon: 'none',
      });
    } finally {
      setIsActionLoading(false);
    }
  };

  // 离开房间
  const handleLeaveRoom = async () => {
    if (!roomId) return;
    
    try {
      setIsActionLoading(true);
      await leaveRoom(roomId);
      
      Taro.showToast({
        title: '已离开房间',
        icon: 'success',
      });
      
      // 返回上一页
      Taro.navigateBack();
    } catch (error) {
      console.error('离开房间失败:', error);
      Taro.showToast({
        title: '离开房间失败',
        icon: 'none',
      });
    } finally {
      setIsActionLoading(false);
    }
  };

  // 渲染玩家列表
  const renderPlayers = () => {
    if (!room || !room.players || room.players.length === 0) {
      return (
        <View className='turtle-soup-player__empty-players'>
          <FaUsers color="#999" size={18} style={{ marginRight: '8px' }} />
          <Text>等待其他玩家加入...</Text>
        </View>
      );
    }
    
    return (
      <View className='turtle-soup-player__players'>
        {room.players.map(player => (
          <View key={player.userId} className='turtle-soup-player__player-item'>
            <PlayerAvatar 
              player={player}
              size='small'
              showStatus
              showName
              showTag={player.role === PlayerRole.HOST}
            />
          </View>
        ))}
      </View>
    );
  };

  // 渲染游戏状态
  const renderGameStatus = () => {
    if (!room) return null;
    
    let statusText = '';
    let statusClass = '';
    
    switch (room.status) {
      case RoomStatus.WAITING:
        statusText = '等待开始';
        statusClass = 'waiting';
        break;
      case RoomStatus.PLAYING:
        if (gameData && gameData.gameState) {
          switch (gameData.gameState) {
            case GameStatus.PLAYING:
              statusText = '游戏进行中';
              statusClass = 'playing';
              break;
            case GameStatus.REVEALING:
              statusText = '揭示答案中';
              statusClass = 'revealing';
              break;
            case GameStatus.COMPLETED:
              statusText = '游戏已结束';
              statusClass = 'completed';
              break;
            default:
              statusText = '未知状态';
              statusClass = 'waiting';
          }
        } else {
          statusText = '游戏进行中';
          statusClass = 'playing';
        }
        break;
      case RoomStatus.ENDED:
        statusText = '房间已关闭';
        statusClass = 'ended';
        break;
      default:
        statusText = '未知状态';
        statusClass = 'waiting';
    }
    
    return (
      <View className={`turtle-soup-player__status turtle-soup-player__status--${statusClass}`}>
        <Text>{statusText}</Text>
      </View>
    );
  };

  // 渲染游戏内容
  const renderGameContent = () => {
    if (!room || !gameData) return null;
    
    return (
      <View className='turtle-soup-player__content'>
        {/* 游戏状态提示 */}
        {room.status === RoomStatus.WAITING && (
          <View className='turtle-soup-player__waiting-tip'>
            <FaInfoCircle color="#666" size={18} style={{ marginRight: '8px' }} />
            <Text>请等待主持人开始游戏...</Text>
          </View>
        )}
        
        {room.status === RoomStatus.PLAYING && (
          <>
            {/* 谜题标题 */}
            <View className='turtle-soup-player__question-header'>
              <Text className='turtle-soup-player__question-category'>{gameData.question.category}</Text>
              <Text className='turtle-soup-player__question-difficulty'>难度: {gameData.question.difficultyLevel}</Text>
            </View>
            
            {/* 汤面 */}
            <View className='turtle-soup-player__question-section'>
              <Text className='turtle-soup-player__section-title'>
                <FaQuestion color="#333" size={14} style={{ marginRight: '8px' }} />
                谜题
              </Text>
              <View className='turtle-soup-player__soup-title'>
                <Text>{gameData.question.title}</Text>
              </View>
            </View>
            
            {/* 已揭示线索 */}
            {gameData.revealedClues && gameData.revealedClues.length > 0 && (
              <View className='turtle-soup-player__question-section'>
                <Text className='turtle-soup-player__section-title'>已揭示线索</Text>
                <View className='turtle-soup-player__revealed-clues'>
                  {gameData.revealedClues.map((clue, index) => (
                    <View key={index} className='turtle-soup-player__clue'>
                      <Text className='turtle-soup-player__clue-type'>
                        {clue.type === 'text' ? '文本线索' : '图片线索'}
                      </Text>
                      <Text className='turtle-soup-player__clue-value'>{clue.value}</Text>
                    </View>
                  ))}
                </View>
              </View>
            )}
            
            {/* 答案提交区域 */}
            {gameData.gameState === GameStatus.PLAYING && (
              <View className='turtle-soup-player__answer-section'>
                <Text className='turtle-soup-player__section-title'>提交您的答案</Text>
                <View className='turtle-soup-player__answer-input'>
                  <Textarea
                    className='turtle-soup-player__textarea'
                    placeholder='请输入您对谜题的解答...'
                    value={answer}
                    onInput={handleAnswerChange}
                    disabled={hasSubmitted || isActionLoading}
                    maxlength={500}
                    showCount
                  />
                </View>
                <Button 
                  type='primary' 
                  block
                  loading={isActionLoading}
                  onClick={handleSubmitAnswer}
                  disabled={hasSubmitted || !answer.trim()}
                  className='turtle-soup-player__submit-btn'
                  icon={<FaPaperPlane size={16} />}
                >
                  {hasSubmitted ? '已提交答案' : '提交答案'}
                </Button>
              </View>
            )}
            
            {/* 答案揭晓 */}
            {gameData.gameState === GameStatus.COMPLETED && (
              <View className='turtle-soup-player__answer-section'>
                <Text className='turtle-soup-player__section-title'>谜题答案</Text>
                <View className='turtle-soup-player__final-answer'>
                  <Text className='turtle-soup-player__final-answer-text'>
                    {gameData.answer || '等待主持人揭晓谜底...'}
                  </Text>
                </View>
              </View>
            )}
          </>
        )}
      </View>
    );
  };

  if (isLoading && !room) {
    return <View className='turtle-soup-player__loading'>加载中...</View>;
  }

  if (!room) {
    return <View className='turtle-soup-player__error'>房间不存在或已关闭</View>;
  }

  return (
    <View className='turtle-soup-player'>
      <View className='turtle-soup-player__header'>
        <View className='turtle-soup-player__title-section'>
          <Text className='turtle-soup-player__title'>海龟汤</Text>
          {renderGameStatus()}
        </View>
        <View className='turtle-soup-player__room-info'>
          <Text className='turtle-soup-player__room-code'>房间码: {roomCode}</Text>
        </View>
      </View>
      
      <View className='turtle-soup-player__players-section'>
        <Text className='turtle-soup-player__section-title'>
          <FaUsers color="#333" size={14} style={{ marginRight: '8px' }} />
          玩家列表 ({room.players ? room.players.length : 0})
        </Text>
        {renderPlayers()}
      </View>
      
      <ScrollView 
        className='turtle-soup-player__scroll-section'
        scrollY
        enableBackToTop
      >
        {renderGameContent()}
      </ScrollView>
      
      <View className='turtle-soup-player__actions'>
        <Button 
          type='secondary' 
          block
          onClick={handleLeaveRoom}
          loading={isActionLoading}
          icon={<FaSignOutAlt size={16} />}
        >
          离开房间
        </Button>
      </View>
    </View>
  );
};

export default TurtleSoupPlayer; 