import React, { useState, useEffect } from 'react';
import Taro, { useRouter } from '@tarojs/taro';
import { View, Text, Image, ScrollView } from '@tarojs/components';
import Button from '../../../../components/base/Button';
import PlayerAvatar from '../../../../components/room/PlayerAvatar';
import { getRoomInfo, startGame, endGame } from '../../../../services/api';
import { Room, TurtleSoupGameData } from '../../../../interfaces';
import { GameStatus, PlayerRole, RoomStatus } from '../../../../constants';
import { TurtleSoupGameService } from '../../../../services/game';
import './index.scss';

const TurtleSoupHost: 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 [selectedClue, setSelectedClue] = useState<string | null>(null);

  // 获取房间信息
  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 hostViewData = TurtleSoupGameService.getHostViewData(roomData);
        setGameData(hostViewData);
      }
    } catch (error) {
      console.error('获取房间信息失败:', error);
      Taro.showToast({
        title: '获取房间信息失败',
        icon: 'none',
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 开始游戏
  const handleStartGame = async () => {
    if (!roomId || !room) return;
    
    try {
      setIsActionLoading(true);
      await TurtleSoupGameService.startGame(roomId);
      await fetchRoomInfo();
      
      Taro.showToast({
        title: '游戏已开始',
        icon: 'success',
      });
    } catch (error) {
      console.error('开始游戏失败:', error);
      Taro.showToast({
        title: '开始游戏失败',
        icon: 'none',
      });
    } finally {
      setIsActionLoading(false);
    }
  };

  // 揭示线索
  const handleRevealClue = async () => {
    if (!roomId || !selectedClue) return;
    
    try {
      setIsActionLoading(true);
      await TurtleSoupGameService.revealClue(roomId, selectedClue);
      await fetchRoomInfo();
      setSelectedClue(null);
      
      Taro.showToast({
        title: '线索已揭示',
        icon: 'success',
      });
    } catch (error) {
      console.error('揭示线索失败:', error);
      Taro.showToast({
        title: '揭示线索失败',
        icon: 'none',
      });
    } finally {
      setIsActionLoading(false);
    }
  };

  // 结束游戏
  const handleEndGame = async () => {
    if (!roomId) return;
    
    try {
      setIsActionLoading(true);
      await TurtleSoupGameService.endGame(roomId);
      await fetchRoomInfo();
      
      Taro.showToast({
        title: '游戏已结束',
        icon: 'success',
      });
    } catch (error) {
      console.error('结束游戏失败:', error);
      Taro.showToast({
        title: '结束游戏失败',
        icon: 'none',
      });
    } finally {
      setIsActionLoading(false);
    }
  };

  // 分享房间
  const handleShareRoom = () => {
    if (!roomCode) return;
    
    Taro.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline'],
    });
  };

  // 生成房间码显示
  const renderRoomCode = () => {
    if (!roomCode) return null;
    
    const chars = roomCode.split('');
    return (
      <View className='turtle-soup-host__room-code'>
        <Text className='turtle-soup-host__room-code-label'>房间码:</Text>
        <View className='turtle-soup-host__room-code-content'>
          {chars.map((char, index) => (
            <Text key={index} className='turtle-soup-host__room-code-char'>{char}</Text>
          ))}
        </View>
      </View>
    );
  };

  // 渲染玩家列表
  const renderPlayers = () => {
    if (!room || !room.players || room.players.length === 0) {
      return (
        <View className='turtle-soup-host__empty-players'>
          <Text>等待玩家加入...</Text>
        </View>
      );
    }
    
    return (
      <View className='turtle-soup-host__players'>
        {room.players.map(player => (
          <View key={player.userId} className='turtle-soup-host__player-item'>
            <PlayerAvatar 
              player={player}
              size='small'
              showStatus
              showName
              showTag={player.role === PlayerRole.HOST}
            />
            {gameData && gameData.playerAnswers && gameData.playerAnswers[player.userId] && (
              <Text className='turtle-soup-host__player-answered'>已回答</Text>
            )}
          </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-host__status turtle-soup-host__status--${statusClass}`}>
        <Text>{statusText}</Text>
      </View>
    );
  };

  // 渲染游戏内容
  const renderGameContent = () => {
    if (!room || !gameData) return null;
    
    return (
      <View className='turtle-soup-host__content'>
        {/* 谜题标题 */}
        <View className='turtle-soup-host__question-header'>
          <Text className='turtle-soup-host__question-category'>{gameData.question.category}</Text>
          <Text className='turtle-soup-host__question-difficulty'>难度: {gameData.question.difficultyLevel}</Text>
        </View>
        
        {/* 汤面 */}
        <View className='turtle-soup-host__question-section'>
          <Text className='turtle-soup-host__section-title'>汤面</Text>
          <View className='turtle-soup-host__soup-title'>
            <Text>{gameData.question.title}</Text>
          </View>
        </View>
        
        {/* 汤底 */}
        <View className='turtle-soup-host__question-section'>
          <Text className='turtle-soup-host__section-title'>汤底（仅主持人可见）</Text>
          <View className='turtle-soup-host__soup-answer'>
            <Text>{gameData.question.answer}</Text>
          </View>
        </View>
        
        {/* 引导问题 */}
        {gameData.question.guidingQuestions && gameData.question.guidingQuestions.length > 0 && (
          <View className='turtle-soup-host__question-section'>
            <Text className='turtle-soup-host__section-title'>引导问题</Text>
            <View className='turtle-soup-host__guiding-questions'>
              {gameData.question.guidingQuestions.map((question, index) => (
                <View key={index} className='turtle-soup-host__guiding-question'>
                  <Text className='turtle-soup-host__guiding-number'>{index + 1}.</Text>
                  <Text className='turtle-soup-host__guiding-text'>{question}</Text>
                </View>
              ))}
            </View>
          </View>
        )}
        
        {/* 已揭示线索 */}
        {gameData.revealedClues && gameData.revealedClues.length > 0 && (
          <View className='turtle-soup-host__question-section'>
            <Text className='turtle-soup-host__section-title'>已揭示线索</Text>
            <View className='turtle-soup-host__revealed-clues'>
              {gameData.revealedClues.map((clueId, index) => {
                const clue = gameData.question.keyClues.find(c => c.type + c.value === clueId);
                if (!clue) return null;
                
                return (
                  <View key={index} className='turtle-soup-host__clue'>
                    <Text className='turtle-soup-host__clue-type'>{clue.type === 'text' ? '文本线索' : '图片线索'}</Text>
                    <Text className='turtle-soup-host__clue-value'>{clue.value}</Text>
                  </View>
                );
              })}
            </View>
          </View>
        )}
        
        {/* 可用线索 */}
        {gameData.availableClues && gameData.availableClues.length > 0 && room.status === RoomStatus.PLAYING && (
          <View className='turtle-soup-host__question-section'>
            <Text className='turtle-soup-host__section-title'>可揭示线索</Text>
            <View className='turtle-soup-host__available-clues'>
              {gameData.availableClues.map((clue, index) => (
                <View 
                  key={index} 
                  className={`turtle-soup-host__clue ${selectedClue === clue.type + clue.value ? 'turtle-soup-host__clue--selected' : ''}`}
                  onClick={() => setSelectedClue(clue.type + clue.value)}
                >
                  <Text className='turtle-soup-host__clue-type'>{clue.type === 'text' ? '文本线索' : '图片线索'}</Text>
                  <Text className='turtle-soup-host__clue-value'>{clue.value}</Text>
                </View>
              ))}
            </View>
            {selectedClue && (
              <Button 
                type='primary' 
                size='small'
                loading={isActionLoading}
                onClick={handleRevealClue}
                className='turtle-soup-host__reveal-btn'
              >
                揭示选中线索
              </Button>
            )}
          </View>
        )}
        
        {/* 玩家回答 */}
        {gameData.playerAnswers && Object.keys(gameData.playerAnswers).length > 0 && (
          <View className='turtle-soup-host__question-section'>
            <Text className='turtle-soup-host__section-title'>玩家回答</Text>
            <View className='turtle-soup-host__player-answers'>
              {Object.entries(gameData.playerAnswers).map(([userId, answer]) => {
                const player = room.players.find(p => p.userId === userId);
                if (!player) return null;
                
                return (
                  <View key={userId} className='turtle-soup-host__player-answer'>
                    <View className='turtle-soup-host__player-info'>
                      <Image 
                        className='turtle-soup-host__player-avatar' 
                        src={player.avatarUrl}
                        mode='aspectFill'
                      />
                      <Text className='turtle-soup-host__player-name'>{player.nickName}</Text>
                    </View>
                    <Text className='turtle-soup-host__answer-content'>{answer as string}</Text>
                  </View>
                );
              })}
            </View>
          </View>
        )}
      </View>
    );
  };

  // 渲染底部操作区域
  const renderActions = () => {
    if (!room) return null;
    
    return (
      <View className='turtle-soup-host__actions'>
        {room.status === RoomStatus.WAITING && (
          <Button 
            type='primary' 
            block
            loading={isActionLoading}
            onClick={handleStartGame}
            disabled={!room.players || room.players.length < 2}
          >
            开始游戏
          </Button>
        )}
        
        {room.status === RoomStatus.PLAYING && (
          <Button 
            type='primary' 
            block
            loading={isActionLoading}
            onClick={handleEndGame}
          >
            结束游戏
          </Button>
        )}
        
        <Button 
          type='secondary' 
          block
          onClick={handleShareRoom}
          className='turtle-soup-host__share-btn'
        >
          分享房间
        </Button>
      </View>
    );
  };

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

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

  return (
    <View className='turtle-soup-host'>
      <View className='turtle-soup-host__header'>
        <View className='turtle-soup-host__title-section'>
          <Text className='turtle-soup-host__title'>海龟汤</Text>
          {renderGameStatus()}
        </View>
        {renderRoomCode()}
      </View>
      
      <View className='turtle-soup-host__players-section'>
        <Text className='turtle-soup-host__section-title'>玩家列表 ({room.players ? room.players.length : 0})</Text>
        {renderPlayers()}
      </View>
      
      <ScrollView 
        className='turtle-soup-host__scroll-section'
        scrollY
        enableBackToTop
      >
        {renderGameContent()}
      </ScrollView>
      
      {renderActions()}
    </View>
  );
};

export default TurtleSoupHost; 