import React, { useState } from 'react';
import Taro from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import { FaDoorOpen, FaQrcode, FaInfoCircle, FaQuestionCircle, FaRegClock, FaExclamationCircle } from 'react-icons/fa';
import Button from '../../../components/base/Button';
import RoomCodeInput from '../../../components/room/RoomCodeInput';
import { joinRoom } from '../../../services/api';
import { ROOM_CODE_LENGTH } from '../../../constants';
import './index.scss';

const JoinRoom: React.FC = () => {
  const [roomCode, setRoomCode] = useState<string>('');
  const [isJoining, setIsJoining] = useState<boolean>(false);

  // 处理房间码变化
  const handleRoomCodeChange = (value: string) => {
    setRoomCode(value);
  };

  // 处理房间码输入完成
  const handleRoomCodeComplete = (value: string) => {
    if (value.length === ROOM_CODE_LENGTH) {
      handleJoinRoom();
    }
  };

  // 扫码加入房间
  const handleScanCode = async () => {
    try {
      const { result } = await Taro.scanCode({
        scanType: ['qrCode'],
      });
      
      // 解析扫描结果
      if (result && result.includes('roomCode=')) {
        const code = result.split('roomCode=')[1].slice(0, ROOM_CODE_LENGTH);
        if (code.length === ROOM_CODE_LENGTH) {
          setRoomCode(code);
          handleJoinRoom(code);
        } else {
          Taro.showToast({
            title: '无效的房间码',
            icon: 'none',
          });
        }
      } else {
        Taro.showToast({
          title: '无效的二维码',
          icon: 'none',
        });
      }
    } catch (error) {
      console.error('扫码失败:', error);
    }
  };

  // 加入房间
  const handleJoinRoom = async (code?: string) => {
    const finalCode = code || roomCode;
    
    if (finalCode.length !== ROOM_CODE_LENGTH) {
      Taro.showToast({
        title: `请输入${ROOM_CODE_LENGTH}位房间码`,
        icon: 'none',
      });
      return;
    }

    try {
      setIsJoining(true);
      
      const room = await joinRoom(finalCode);
      
      // 加入成功，跳转到对应游戏页面
      Taro.navigateTo({
        url: `/pages/games/${room.gameId}/player/index?roomId=${room.roomId}&roomCode=${room.roomCode}`,
      });
      
    } catch (error) {
      console.error('加入房间失败:', error);
      Taro.showToast({
        title: '加入房间失败，请检查房间码是否正确',
        icon: 'none',
      });
    } finally {
      setIsJoining(false);
    }
  };

  return (
    <View className='join-room'>
      <View className='join-room__header'>
        <Text className='join-room__title'>加入房间</Text>
        <Text className='join-room__subtitle'>输入6位房间码或扫描二维码加入</Text>
      </View>

      <View className='join-room__input-section'>
        <RoomCodeInput
          value={roomCode}
          onChange={handleRoomCodeChange}
          onComplete={handleRoomCodeComplete}
          length={ROOM_CODE_LENGTH}
        />
      </View>

      <View className='join-room__actions'>
        <Button 
          type='primary' 
          block
          loading={isJoining}
          onClick={() => handleJoinRoom()}
          className='join-room__join-btn'
          icon={<FaDoorOpen size={18} />}
        >
          加入房间
        </Button>
        
        <Button 
          type='secondary' 
          block
          onClick={handleScanCode}
          className='join-room__scan-btn'
          icon={<FaQrcode size={18} />}
        >
          扫码加入
        </Button>
      </View>

      <View className='join-room__recent'>
        <Text className='join-room__recent-title'>
          <FaRegClock size={16} color="#666" style={{ marginRight: '8px' }} />
          最近加入的房间
        </Text>
        <View className='join-room__empty-tip'>
          <FaExclamationCircle size={48} color="#cccccc" />
          <Text className='join-room__empty-text'>暂无最近加入的房间</Text>
        </View>
      </View>

      <View className='join-room__help'>
        <Text className='join-room__help-title'>
          <FaQuestionCircle size={16} color="#666" style={{ marginRight: '8px' }} />
          如何获取房间码？
        </Text>
        <View className='join-room__help-item'>
          <FaInfoCircle size={12} color="#4285f4" style={{ marginRight: '8px' }} />
          <Text className='join-room__help-text'>向游戏主持人获取6位房间码</Text>
        </View>
        <View className='join-room__help-item'>
          <FaInfoCircle size={12} color="#4285f4" style={{ marginRight: '8px' }} />
          <Text className='join-room__help-text'>扫描主持人分享的房间二维码</Text>
        </View>
        <View className='join-room__help-item'>
          <FaInfoCircle size={12} color="#4285f4" style={{ marginRight: '8px' }} />
          <Text className='join-room__help-text'>从微信群或朋友分享的链接进入</Text>
        </View>
      </View>
    </View>
  );
};

export default JoinRoom; 