import React, { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { View, ScrollView, Input, Image } from '@tarojs/components';
import GameCard from '../../components/base/GameCard';
import { Game } from '../../interfaces';
import { getGames } from '../../services/api';
import { GameCategories } from '../../constants';
import './index.scss';

interface Category {
  id: string;
  name: string;
}

const GamePlaza: React.FC = () => {
  const [games, setGames] = useState<Game[]>([]);
  const [filteredGames, setFilteredGames] = useState<Game[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [activeCategory, setActiveCategory] = useState<string>('popular');
  const [isLoading, setIsLoading] = useState(false);

  // 添加内置分类
  const allCategories: Category[] = [
    { id: 'popular', name: '推荐' },
    { id: 'puzzle', name: '解谜' },
    { id: 'social', name: '社交' },
    { id: 'knowledge', name: '知识' },
  ];

  // 获取游戏列表
  useEffect(() => {
    fetchGames();
  }, []);

  // 根据分类和搜索关键词筛选游戏
  useEffect(() => {
    filterGames();
  }, [games, activeCategory, searchKeyword]);

  // 获取游戏列表
  const fetchGames = async () => {
    try {
      setIsLoading(true);
      const data = await getGames();
      setGames(data);
    } catch (error) {
      console.error('获取游戏列表失败:', error);
      Taro.showToast({
        title: '获取游戏列表失败',
        icon: 'none',
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 筛选游戏
  const filterGames = () => {
    let filtered = [...games];

    // 按分类筛选
    if (activeCategory !== 'popular') {
      filtered = filtered.filter(game => game.category === activeCategory);
    } else {
      // 推荐分类按评分排序
      filtered.sort((a, b) => b.rating - a.rating);
    }

    // 按关键词搜索
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(
        game => 
          game.gameName.toLowerCase().includes(keyword) || 
          game.gameDescription.toLowerCase().includes(keyword)
      );
    }

    setFilteredGames(filtered);
  };

  // 处理分类切换
  const handleCategoryChange = (categoryId: string) => {
    setActiveCategory(categoryId);
  };

  // 处理搜索
  const handleSearch = (e) => {
    setSearchKeyword(e.detail.value);
  };

  // 处理游戏卡片点击
  const handleGameClick = (game: Game) => {
    Taro.navigateTo({
      url: `/pages/game-detail/index?gameId=${game.gameId}`,
    });
  };

  // 处理下拉刷新
  const handleRefresh = async () => {
    await fetchGames();
    Taro.stopPullDownRefresh();
  };

  return (
    <View className='game-plaza'>
      {/* 头部搜索 */}
      <View className='game-plaza__header'>
        <View className='game-plaza__search'>
          <View className='game-plaza__search-icon'>
            🔍
          </View>
          <Input
            className='game-plaza__search-input'
            type='text'
            placeholder='搜索游戏...'
            value={searchKeyword}
            onInput={handleSearch}
          />
        </View>
      </View>

      {/* 分类tabs */}
      <ScrollView
        className='game-plaza__categories'
        scrollX
        scrollWithAnimation
      >
        {allCategories.map(category => (
          <View
            key={category.id}
            className={`game-plaza__category ${
              activeCategory === category.id ? 'game-plaza__category--active' : ''
            }`}
            onClick={() => handleCategoryChange(category.id)}
          >
            {category.name}
          </View>
        ))}
      </ScrollView>

      {/* 游戏列表 */}
      <ScrollView
        className='game-plaza__games'
        scrollY
        enableBackToTop
        onScrollToLower={() => {}}
        refresherEnabled
        refresherTriggered={isLoading}
        onRefresherRefresh={handleRefresh}
      >
        {filteredGames.length > 0 ? (
          filteredGames.map(game => (
            <GameCard key={game.gameId} game={game} onClick={handleGameClick} />
          ))
        ) : (
          <View className='game-plaza__empty'>
            {isLoading ? '加载中...' : '暂无游戏'}
          </View>
        )}
      </ScrollView>
    </View>
  );
};

export default GamePlaza; 