import React, { useState } from 'react';
import Taro, { useRouter } from '@tarojs/taro';
import { View, Text, Picker } from '@tarojs/components';
import Button from '../../../components/base/Button';
import { createRoom } from '../../../services/api';
import { GameTheme, GameDifficulty, MAX_PLAYERS } from '../../../constants';
import './index.scss';

const CreateRoom: React.FC = () => {
  const router = useRouter();
  const { gameId, gameName } = router.params;
  
  const [maxPlayers, setMaxPlayers] = useState<number>(4);
  const [theme, setTheme] = useState<string>(GameTheme.CLASSIC);
  const [difficulty, setDifficulty] = useState<string>(GameDifficulty.MEDIUM);
  const [isCreating, setIsCreating] = useState<boolean>(false);

  // 玩家人数选项
  const playerOptions = Array.from({ length: MAX_PLAYERS }, (_, i) => i + 1);
  
  // 主题选项
  const themeOptions = [
    { value: GameTheme.CLASSIC, label: '经典' },
    { value: GameTheme.UNIVERSAL_STUDIOS, label: '环球影城' },
    { value: GameTheme.DISNEY, label: '迪士尼' },
    { value: GameTheme.FANTASY, label: '奇幻' },
  ];
  
  // 难度选项
  const difficultyOptions = [
    { value: GameDifficulty.EASY, label: '简单' },
    { value: GameDifficulty.MEDIUM, label: '中等' },
    { value: GameDifficulty.HARD, label: '困难' },
  ];

  // 创建房间
  const handleCreateRoom = async () => {
    if (!gameId) {
      Taro.showToast({
        title: '游戏ID不能为空',
        icon: 'none',
      });
      return;
    }

    try {
      setIsCreating(true);
      
      const room = await createRoom({
        gameId,
        maxPlayers,
        theme,
        difficulty,
      });

      // 创建成功，跳转到房间页面
      Taro.navigateTo({
        url: `/pages/games/${gameId}/host/index?roomId=${room.roomId}&roomCode=${room.roomCode}`,
      });
      
    } catch (error) {
      console.error('创建房间失败:', error);
      Taro.showToast({
        title: '创建房间失败',
        icon: 'none',
      });
    } finally {
      setIsCreating(false);
    }
  };

  // 处理玩家人数变化
  const handlePlayerChange = (e) => {
    const index = e.detail.value;
    setMaxPlayers(playerOptions[index]);
  };

  // 处理主题变化
  const handleThemeChange = (e) => {
    const index = e.detail.value;
    setTheme(themeOptions[index].value);
  };

  // 处理难度变化
  const handleDifficultyChange = (e) => {
    const index = e.detail.value;
    setDifficulty(difficultyOptions[index].value);
  };

  return (
    <View className='create-room'>
      <View className='create-room__header'>
        <Text className='create-room__title'>创建房间</Text>
        <Text className='create-room__subtitle'>{gameName || '未知游戏'}</Text>
      </View>

      <View className='create-room__form'>
        {/* 玩家人数 */}
        <View className='create-room__form-item'>
          <Text className='create-room__label'>最大玩家人数</Text>
          <Picker 
            mode='selector' 
            range={playerOptions}
            onChange={handlePlayerChange}
            value={playerOptions.indexOf(maxPlayers)}
          >
            <View className='create-room__picker'>
              <Text>{maxPlayers}人</Text>
              <Text className='create-room__picker-arrow'>▼</Text>
            </View>
          </Picker>
        </View>

        {/* 游戏主题 */}
        <View className='create-room__form-item'>
          <Text className='create-room__label'>游戏主题</Text>
          <Picker 
            mode='selector' 
            range={themeOptions.map(item => item.label)}
            onChange={handleThemeChange}
            value={themeOptions.findIndex(item => item.value === theme)}
          >
            <View className='create-room__picker'>
              <Text>{themeOptions.find(item => item.value === theme)?.label}</Text>
              <Text className='create-room__picker-arrow'>▼</Text>
            </View>
          </Picker>
        </View>

        {/* 游戏难度 */}
        <View className='create-room__form-item'>
          <Text className='create-room__label'>游戏难度</Text>
          <Picker 
            mode='selector' 
            range={difficultyOptions.map(item => item.label)}
            onChange={handleDifficultyChange}
            value={difficultyOptions.findIndex(item => item.value === difficulty)}
          >
            <View className='create-room__picker'>
              <Text>{difficultyOptions.find(item => item.value === difficulty)?.label}</Text>
              <Text className='create-room__picker-arrow'>▼</Text>
            </View>
          </Picker>
        </View>
      </View>

      <View className='create-room__tips'>
        <Text className='create-room__tips-title'>温馨提示</Text>
        <View className='create-room__tip-item'>
          <Text className='create-room__tip-dot'>•</Text>
          <Text className='create-room__tip-text'>创建房间后，其他玩家可通过房间码加入</Text>
        </View>
        <View className='create-room__tip-item'>
          <Text className='create-room__tip-dot'>•</Text>
          <Text className='create-room__tip-text'>房主可以控制游戏开始、结束和重新开始</Text>
        </View>
        <View className='create-room__tip-item'>
          <Text className='create-room__tip-dot'>•</Text>
          <Text className='create-room__tip-text'>游戏中如遇问题，可点击右上角"..."按钮反馈</Text>
        </View>
      </View>

      <View className='create-room__footer'>
        <Button 
          type='primary' 
          block
          loading={isCreating}
          onClick={handleCreateRoom}
        >
          创建并进入房间
        </Button>
      </View>
    </View>
  );
};

export default CreateRoom; 