import React, { useState, useEffect } from 'react';
import Taro, { useRouter } from '@tarojs/taro';
import { View, Image, Text, ScrollView } from '@tarojs/components';
import { Game } from '../../interfaces';
import { getGameDetail } from '../../services/api';
import Button from '../../components/base/Button';
import './index.scss';

const GameDetail: React.FC = () => {
  const router = useRouter();
  const { gameId } = router.params;
  const [game, setGame] = useState<Game | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 获取游戏详情
  useEffect(() => {
    if (gameId) {
      fetchGameDetail(gameId);
    }
  }, [gameId]);

  // 获取游戏详情
  const fetchGameDetail = async (id: string) => {
    try {
      setIsLoading(true);
      const data = await getGameDetail(id);
      setGame(data);
    } catch (error) {
      console.error('获取游戏详情失败:', error);
      Taro.showToast({
        title: '获取游戏详情失败',
        icon: 'none',
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 创建房间
  const handleCreateRoom = () => {
    if (!game) return;
    
    Taro.navigateTo({
      url: `/pages/room/create/index?gameId=${game.gameId}&gameName=${encodeURIComponent(game.gameName)}`,
    });
  };

  // 分享游戏
  const handleShare = () => {
    Taro.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline'],
    });
  };

  if (isLoading) {
    return <View className='game-detail__loading'>加载中...</View>;
  }

  if (!game) {
    return <View className='game-detail__error'>游戏不存在</View>;
  }

  return (
    <View className='game-detail'>
      {/* 游戏封面 */}
      <View className='game-detail__cover'>
        <Image
          className='game-detail__image'
          src={game.coverImage || 'https://placeholder.com/800x400'}
          mode='aspectFill'
        />
        <View className='game-detail__info-overlay'>
          <Text className='game-detail__title'>{game.gameName}</Text>
          <View className='game-detail__meta'>
            <Text className='game-detail__players'>{`${game.minPlayers}-${game.maxPlayers}人`}</Text>
            <Text className='game-detail__time'>{game.timeEstimate}</Text>
          </View>
          <View className='game-detail__rating'>
            {Array(5).fill(0).map((_, index) => (
              <Text
                key={index}
                className={`game-detail__star ${index < Math.floor(game.rating) ? 'game-detail__star--active' : ''}`}
              >
                ★
              </Text>
            ))}
            <Text className='game-detail__rating-value'>{game.rating.toFixed(1)}</Text>
          </View>
        </View>
      </View>

      {/* 游戏内容 */}
      <ScrollView className='game-detail__content' scrollY>
        {/* 游戏标签 */}
        <View className='game-detail__tags'>
          {game.tags.map((tag, index) => (
            <Text key={index} className='game-detail__tag'>{tag}</Text>
          ))}
        </View>

        {/* 游戏描述 */}
        <View className='game-detail__section'>
          <Text className='game-detail__section-title'>游戏介绍</Text>
          <Text className='game-detail__description'>{game.gameDescription}</Text>
        </View>

        {/* 游戏规则 */}
        <View className='game-detail__section'>
          <Text className='game-detail__section-title'>游戏规则</Text>
          {game.gameId === 'turtle-soup' && (
            <View className='game-detail__rules'>
              <View className='game-detail__rule-item'>
                <Text className='game-detail__rule-step'>1.</Text>
                <Text className='game-detail__rule-text'>主持人公布谜题开头（汤面），玩家尝试猜测背后的真相</Text>
              </View>
              <View className='game-detail__rule-item'>
                <Text className='game-detail__rule-step'>2.</Text>
                <Text className='game-detail__rule-text'>玩家提问（只能问是非问题）</Text>
              </View>
              <View className='game-detail__rule-item'>
                <Text className='game-detail__rule-step'>3.</Text>
                <Text className='game-detail__rule-text'>主持人回答"是"、"否"或"无关"</Text>
              </View>
              <View className='game-detail__rule-item'>
                <Text className='game-detail__rule-step'>4.</Text>
                <Text className='game-detail__rule-text'>玩家持续提问直到猜出答案</Text>
              </View>
              <View className='game-detail__rule-item'>
                <Text className='game-detail__rule-step'>5.</Text>
                <Text className='game-detail__rule-text'>主持人揭晓谜底（汤底）</Text>
              </View>
            </View>
          )}
        </View>

        {/* 游戏示例 */}
        <View className='game-detail__section'>
          <Text className='game-detail__section-title'>游戏示例</Text>
          {game.gameId === 'turtle-soup' && (
            <View className='game-detail__example'>
              <View className='game-detail__example-item'>
                <Text className='game-detail__example-title'>汤面：</Text>
                <Text className='game-detail__example-text'>一个男人收到了一块神秘的手表，看上去很普通，戴上后，一周后他自杀了。为什么？</Text>
              </View>
              <View className='game-detail__example-item'>
                <Text className='game-detail__example-title'>提问：</Text>
                <Text className='game-detail__example-text'>手表有特殊功能吗？</Text>
                <Text className='game-detail__example-answer'>是</Text>
              </View>
              <View className='game-detail__example-item'>
                <Text className='game-detail__example-title'>提问：</Text>
                <Text className='game-detail__example-text'>他因为手表的功能而自杀的吗？</Text>
                <Text className='game-detail__example-answer'>是</Text>
              </View>
              <View className='game-detail__example-item'>
                <Text className='game-detail__example-title'>汤底：</Text>
                <Text className='game-detail__example-text'>这块手表可以让佩戴者看到未来。男人看到了自己一周后的未来是自杀，他不相信这是命运，认为是手表在骗他。为了证明手表是错的，他决定活过那一天，但在那一天，他意外发现自己最爱的人背叛了他，心灰意冷之下自杀了，恰好印证了手表的预言。</Text>
              </View>
            </View>
          )}
        </View>
      </ScrollView>

      {/* 底部操作栏 */}
      <View className='game-detail__footer'>
        <Button 
          type='secondary' 
          onClick={handleShare}
          className='game-detail__share-btn'
        >
          分享游戏
        </Button>
        <Button 
          type='primary' 
          onClick={handleCreateRoom}
          className='game-detail__create-btn'
        >
          创建房间
        </Button>
      </View>
    </View>
  );
};

export default GameDetail; 