import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/game_model.dart';

class GameController {
  final _supabase = Supabase.instance.client;

  String get myUserId => _supabase.auth.currentUser?.id ?? '';

  // LER JOGOS
  Stream<List<Game>> get gamesStream {
    return _supabase
        .from('games')
        .stream(primaryKey: ['id'])
        .eq('user_id', myUserId)
        .asyncMap((event) async {
          final data = await _supabase
              .from('games')
              .select()
              .eq('user_id', myUserId)
              .order('game_date', ascending: false);
              
          // O Game.fromMap agora faz o trabalho sujo todo!
          return data.map((json) => Game.fromMap(json)).toList();
        });
  }

  // LER JOGOS COM FILTROS
  Stream<List<Game>> getFilteredGames({required String teamFilter, required String seasonFilter}) {
    return _supabase
        .from('games') 
        .stream(primaryKey: ['id'])
        .eq('user_id', myUserId)
        .asyncMap((event) async {
          
          var query = _supabase.from('games').select().eq('user_id', myUserId);

          if (seasonFilter != 'Todas') {
            query = query.eq('season', seasonFilter);
          }

          final data = await query.order('game_date', ascending: false);
          
          List<Game> games = data.map((json) => Game.fromMap(json)).toList();

          if (teamFilter != 'Todas') {
            games = games.where((g) => g.myTeam == teamFilter || g.opponentTeam == teamFilter).toList();
          }

          return games;
        });
  }   

  // CRIAR JOGO
  Future<String?> createGame(String myTeam, String opponent, String season) async {
    try {
      final response = await _supabase.from('games').insert({
        'user_id': myUserId,
        'my_team': myTeam,
        'opponent_team': opponent,
        'season': season,
        'my_score': 0,
        'opponent_score': 0,
        'status': 'Decorrer', 
        'game_date': DateTime.now().toIso8601String(),
        // 👇 Preenchemos logo com os valores iniciais da tua Base de Dados
        'remaining_seconds': 600, // Assume 10 minutos (600s)
        'my_timeouts': 0,
        'opp_timeouts': 0,
        'current_quarter': 1,
        'top_pts_name': '---',
        'top_ast_name': '---',
        'top_rbs_name': '---',
        'top_def_name': '---',
        'mvp_name': '---',
      }).select().single(); 

      return response['id']?.toString();
    } catch (e) {
      print("Erro ao criar jogo: $e");
      return null;
    }
    
  }
// ELIMINAR JOGO
  Future<bool> deleteGame(String gameId) async {
    try {
      await _supabase.from('games').delete().eq('id', gameId);
      // Como o Supabase tem Cascade Delete (se configurado), vai apagar também 
      // as stats e shot_locations associadas a este game_id automaticamente.
      return true;
    } catch (e) {
      print("Erro ao eliminar jogo: $e");
      return false;
    }
  }
  void dispose() {}
}