import React, { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Button as TaroButton } from '@tarojs/components';
import { FaGamepad, FaUsers, FaRocket, FaSignInAlt } from 'react-icons/fa';
import Button from '../../components/base/Button';
import { login } from '../../services/api';
import { StorageKey } from '../../constants';
import { initCloud } from '../../services/cloud';
import './index.scss';

const Login: React.FC = () => {
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isInitializing, setIsInitializing] = useState<boolean>(true);

  // 初始化云开发环境
  useEffect(() => {
    initializeApp();
  }, []);

  // 初始化应用
  const initializeApp = async () => {
    try {
      // 初始化云开发环境
      await initCloud();
      
      // 检查登录状态
      const token = Taro.getStorageSync(StorageKey.TOKEN);
      if (token) {
        // 已经登录，跳转到首页
        Taro.switchTab({
          url: '/pages/game-plaza/index',
        });
        return;
      }
      
    } catch (error) {
      console.error('初始化失败:', error);
    } finally {
      setIsInitializing(false);
    }
  };

  // 用户登录
  const handleLogin = async () => {
    try {
      setIsLoading(true);
      
      // 获取微信登录凭证
      const { code } = await Taro.login();
      
      // 调用登录接口
      const { token, user } = await login(code);
      
      // 保存登录信息
      Taro.setStorageSync(StorageKey.TOKEN, token);
      Taro.setStorageSync(StorageKey.USER_INFO, JSON.stringify(user));
      
      // 登录成功，跳转到首页
      Taro.switchTab({
        url: '/pages/game-plaza/index',
      });
      
    } catch (error) {
      console.error('登录失败:', error);
      Taro.showToast({
        title: '登录失败，请重试',
        icon: 'none',
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 获取用户信息
  const getUserProfile = async () => {
    try {
      setIsLoading(true);
      
      // 获取用户信息
      const userProfile = await Taro.getUserProfile({
        desc: '用于完善个人资料',
      });
      
      // 保存用户信息
      Taro.setStorageSync('userProfile', JSON.stringify(userProfile));
      
      // 继续登录流程
      await handleLogin();
      
    } catch (error) {
      console.error('获取用户信息失败:', error);
      
      // 如果用户拒绝授权，尝试直接登录
      if (error.errMsg && error.errMsg.includes('fail auth deny')) {
        await handleLogin();
      } else {
        Taro.showToast({
          title: '获取用户信息失败',
          icon: 'none',
        });
      }
    } finally {
      setIsLoading(false);
    }
  };

  if (isInitializing) {
    return (
      <View className='login__loading'>
        <Text>加载中...</Text>
      </View>
    );
  }

  return (
    <View className='login'>
      <View className='login__header'>
        <View className='login__logo'>
          <FaGamepad size={56} color="#4F7FFE" />
        </View>
        <Text className='login__title'>LineFunQueue</Text>
        <Text className='login__subtitle'>排队中的趣味小游戏</Text>
      </View>

      <View className='login__content'>
        <View className='login__feature-list'>
          <View className='login__feature-item'>
            <View className='login__feature-icon'>
              <FaGamepad size={24} color="#4285f4" />
            </View>
            <View className='login__feature-info'>
              <Text className='login__feature-title'>多种互动游戏</Text>
              <Text className='login__feature-desc'>海龟汤、谜语等轻松有趣的游戏</Text>
            </View>
          </View>
          <View className='login__feature-item'>
            <View className='login__feature-icon'>
              <FaUsers size={24} color="#4285f4" />
            </View>
            <View className='login__feature-info'>
              <Text className='login__feature-title'>社交互动</Text>
              <Text className='login__feature-desc'>打破陌生人社交壁垒，促进线下交流</Text>
            </View>
          </View>
          <View className='login__feature-item'>
            <View className='login__feature-icon'>
              <FaRocket size={24} color="#4285f4" />
            </View>
            <View className='login__feature-info'>
              <Text className='login__feature-title'>即开即玩</Text>
              <Text className='login__feature-desc'>无需繁琐注册，扫码即可加入游戏</Text>
            </View>
          </View>
        </View>
      </View>

      <View className='login__footer'>
        <Button
          type='primary'
          block
          loading={isLoading}
          onClick={getUserProfile}
          icon={<FaSignInAlt size={18} />}
        >
          微信登录
        </Button>
        <TaroButton
          className='login__tourist-btn'
          plain
          onClick={handleLogin}
          loading={isLoading}
        >
          游客登录
        </TaroButton>
        <Text className='login__tips'>登录即代表同意《用户协议》和《隐私政策》</Text>
      </View>
    </View>
  );
};

export default Login; 