import React, { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, ScrollView } from '@tarojs/components';
import { FaHistory, FaGamepad, FaCalendarAlt, FaUsers, FaClock } from 'react-icons/fa';
import TabBarLayout from '../../components/layout/TabBarLayout';
import { useUser } from '../../contexts/UserContext';
import { getUserGameHistory } from '../../services/api';
import './index.scss';

interface GameHistoryItem {
  gameId: string;
  gameName: string;
  roomCode: string;
  createdAt: string;
  status: 'playing' | 'completed' | 'interrupted';
  role: 'host' | 'player';
  playerCount: number;
  duration: number;
}

const GameHistoryPage: React.FC = () => {
  const { user } = useUser();
  const [activeTab, setActiveTab] = useState<'all' | 'host' | 'player'>('all');
  const [gameHistory, setGameHistory] = useState<GameHistoryItem[]>([]);
  const [filteredHistory, setFilteredHistory] = useState<GameHistoryItem[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  useEffect(() => {
    if (user && user.userId) {
      fetchGameHistory(user.userId);
    } else {
      // 未登录，跳转到登录页面
      Taro.redirectTo({ url: '/pages/login/index' });
    }
  }, [user]);

  useEffect(() => {
    filterHistory();
  }, [activeTab, gameHistory]);

  const fetchGameHistory = async (userId: string) => {
    try {
      setIsLoading(true);
      const history = await getUserGameHistory(userId);
      setGameHistory(history);
    } catch (error) {
      console.error('获取游戏历史失败:', error);
      Taro.showToast({
        title: '获取游戏历史失败',
        icon: 'none',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const filterHistory = () => {
    if (activeTab === 'all') {
      setFilteredHistory(gameHistory);
    } else {
      setFilteredHistory(gameHistory.filter(item => item.role === activeTab));
    }
  };

  const handleTabChange = (tab: 'all' | 'host' | 'player') => {
    setActiveTab(tab);
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
  };

  const formatDuration = (duration: number) => {
    const hours = Math.floor(duration / 3600);
    const minutes = Math.floor((duration % 3600) / 60);
    return hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`;
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'playing':
        return '进行中';
      case 'completed':
        return '已完成';
      case 'interrupted':
        return '已中断';
      default:
        return '未知状态';
    }
  };

  const getStatusClass = (status: string) => {
    switch (status) {
      case 'playing':
        return 'status-playing';
      case 'completed':
        return 'status-completed';
      case 'interrupted':
        return 'status-interrupted';
      default:
        return 'status-unknown';
    }
  };

  return (
    <TabBarLayout>
      <View className='game-history'>
        <View className='game-history__header'>
          <Text className='game-history__title'>
            <FaHistory size={18} color="#333" style={{ marginRight: '8px' }} />
            游戏历史
          </Text>
        </View>
        
        <View className='game-history__tabs'>
          <View 
            className={`game-history__tab ${activeTab === 'all' ? 'game-history__tab--active' : ''}`}
            onClick={() => handleTabChange('all')}
          >
            全部
          </View>
          <View 
            className={`game-history__tab ${activeTab === 'host' ? 'game-history__tab--active' : ''}`}
            onClick={() => handleTabChange('host')}
          >
            我主持的
          </View>
          <View 
            className={`game-history__tab ${activeTab === 'player' ? 'game-history__tab--active' : ''}`}
            onClick={() => handleTabChange('player')}
          >
            我参与的
          </View>
        </View>
        
        <ScrollView 
          className='game-history__list'
          scrollY
          enableBackToTop
        >
          {isLoading ? (
            <View className='game-history__loading'>加载中...</View>
          ) : filteredHistory.length > 0 ? (
            filteredHistory.map((item, index) => (
              <View key={index} className='game-history__item'>
                <View className='game-history__item-header'>
                  <View className='game-history__game-info'>
                    <View className='game-history__game-icon'>
                      <FaGamepad size={16} color="#4285f4" />
                    </View>
                    <Text className='game-history__game-name'>{item.gameName}</Text>
                  </View>
                  <View className={`game-history__status ${getStatusClass(item.status)}`}>
                    {getStatusText(item.status)}
                  </View>
                </View>
                
                <View className='game-history__item-content'>
                  <View className='game-history__detail-item'>
                    <FaCalendarAlt size={14} color="#666" />
                    <Text className='game-history__detail-text'>{formatDate(item.createdAt)}</Text>
                  </View>
                  <View className='game-history__detail-item'>
                    <Text className='game-history__detail-label'>房间码:</Text>
                    <Text className='game-history__detail-text'>{item.roomCode}</Text>
                  </View>
                  <View className='game-history__detail-item'>
                    <FaUsers size={14} color="#666" />
                    <Text className='game-history__detail-text'>{item.playerCount}人参与</Text>
                  </View>
                  <View className='game-history__detail-item'>
                    <FaClock size={14} color="#666" />
                    <Text className='game-history__detail-text'>时长: {formatDuration(item.duration)}</Text>
                  </View>
                  <View className='game-history__detail-item'>
                    <Text className='game-history__role-badge'>
                      {item.role === 'host' ? '主持人' : '参与者'}
                    </Text>
                  </View>
                </View>
              </View>
            ))
          ) : (
            <View className='game-history__empty'>
              <FaHistory size={36} color="#ccc" />
              <Text className='game-history__empty-text'>暂无游戏记录</Text>
            </View>
          )}
        </ScrollView>
      </View>
    </TabBarLayout>
  );
};

export default GameHistoryPage; 