import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class ActiveTeam {
  final String id;
  final String name;
  final String? logo;
  final int wins;
  final int losses;
  final int draws;

  ActiveTeam({
    required this.id,
    required this.name,
    this.logo,
    this.wins = 0,
    this.losses = 0,
    this.draws = 0,
  });
}

// 🟢 A MÁGICA: Esta variável avisa a Home e a StatusPage ao mesmo tempo quando a equipa muda!
final ValueNotifier<ActiveTeam?> globalActiveTeam = ValueNotifier(null);

// 🟢 FUNÇÃO PARA CARREGAR A EQUIPA AO ABRIR A APP (Lê da Memória e do Supabase)
Future<void> loadGlobalTeam() async {
  final prefs = await SharedPreferences.getInstance();
  final savedId = prefs.getString('last_team_id');
  
  // 1. Carrega rápido da memória (para não piscar o ecrã)
  if (savedId != null) {
    globalActiveTeam.value = ActiveTeam(
      id: savedId,
      name: prefs.getString('last_team_name') ?? "Selecionar Equipa",
      logo: prefs.getString('last_team_logo'),
      wins: prefs.getInt('last_team_wins') ?? 0,
      losses: prefs.getInt('last_team_losses') ?? 0,
      draws: prefs.getInt('last_team_draws') ?? 0,
    );
  }

  // 2. Vai confirmar no Supabase se entraste com esta conta noutro telemóvel!
  final supabase = Supabase.instance.client;
  final userId = supabase.auth.currentUser?.id;
  if (userId == null) return;

  try {
    final profile = await supabase.from('profiles').select('selected_team_id').eq('id', userId).maybeSingle();
    if (profile != null && profile['selected_team_id'] != null) {
      final dbTeamId = profile['selected_team_id'].toString();
      final teamData = await supabase.from('teams').select().eq('id', dbTeamId).maybeSingle();

      if (teamData != null) {
        final newTeam = ActiveTeam(
          id: teamData['id'].toString(),
          name: teamData['name'] ?? 'Desconhecido',
          logo: teamData['image_url'],
          wins: int.tryParse(teamData['wins']?.toString() ?? '0') ?? 0,
          losses: int.tryParse(teamData['losses']?.toString() ?? '0') ?? 0,
          draws: int.tryParse(teamData['draws']?.toString() ?? '0') ?? 0,
        );
        globalActiveTeam.value = newTeam;
        
        // Atualiza a memória do telemóvel para a próxima vez ser rápido
        await prefs.setString('last_team_id', newTeam.id);
        await prefs.setString('last_team_name', newTeam.name);
        if (newTeam.logo != null && newTeam.logo!.isNotEmpty) {
          await prefs.setString('last_team_logo', newTeam.logo!);
        }
        await prefs.setInt('last_team_wins', newTeam.wins);
        await prefs.setInt('last_team_losses', newTeam.losses);
        await prefs.setInt('last_team_draws', newTeam.draws);
      }
    }
  } catch (e) {
    debugPrint("Erro ao carregar equipa do Supabase: $e");
  }
}

// 🟢 FUNÇÃO PARA GUARDAR A EQUIPA (Na Memória e no Supabase)
Future<void> saveGlobalTeam(ActiveTeam team) async {
  globalActiveTeam.value = team; // Atualiza a app inteira!
  
  // 1. Guarda no telemóvel
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString('last_team_id', team.id);
  await prefs.setString('last_team_name', team.name);
  if (team.logo != null && team.logo!.isNotEmpty) {
    await prefs.setString('last_team_logo', team.logo!);
  } else {
    await prefs.remove('last_team_logo');
  }
  await prefs.setInt('last_team_wins', team.wins);
  await prefs.setInt('last_team_losses', team.losses);
  await prefs.setInt('last_team_draws', team.draws);

  // 2. Guarda no Supabase!
  final supabase = Supabase.instance.client;
  final userId = supabase.auth.currentUser?.id;
  if (userId != null) {
    try {
      await supabase.from('profiles').upsert({
        'id': userId,
        'selected_team_id': team.id,
      });
    } catch (e) {
      debugPrint("Erro ao guardar equipa no Supabase: $e");
    }
  }
}