import 'package:flutter/material.dart';
import 'package:playmaker/pages/PlacarPage.dart';
import '../controllers/game_controller.dart';
import '../controllers/team_controller.dart';
import '../models/game_model.dart';
import '../utils/size_extension.dart'; 
import 'dart:math' as math; // 👇 IMPORTANTE PARA O TRAVÃO DE MÃO

// --- CARD DE EXIBIÇÃO DO JOGO ---
class GameResultCard extends StatelessWidget {
  final String gameId, myTeam, opponentTeam, myScore, opponentScore, status, season;
  final String? myTeamLogo, opponentTeamLogo;

  const GameResultCard({
    super.key, required this.gameId, required this.myTeam, required this.opponentTeam,
    required this.myScore, required this.opponentScore, required this.status, required this.season,
    this.myTeamLogo, this.opponentTeamLogo, 
  });

  @override
  Widget build(BuildContext context) {
    final double safeSf = math.min(context.sf, 1.15); // TRAVÃO DO TABLET

    return Container(
      margin: EdgeInsets.only(bottom: 16 * safeSf),
      padding: EdgeInsets.all(16 * safeSf),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20 * safeSf), boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 10 * safeSf)]),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(child: _buildTeamInfo(myTeam, const Color(0xFFE74C3C), myTeamLogo, safeSf)),
          _buildScoreCenter(context, gameId, safeSf),
          Expanded(child: _buildTeamInfo(opponentTeam, Colors.black87, opponentTeamLogo, safeSf)),
        ],
      ),
    );
  }

  Widget _buildTeamInfo(String name, Color color, String? logoUrl, double safeSf) {
    return Column(
      children: [
        CircleAvatar(radius: 24 * safeSf, backgroundColor: color, backgroundImage: (logoUrl != null && logoUrl.isNotEmpty) ? NetworkImage(logoUrl) : null, child: (logoUrl == null || logoUrl.isEmpty) ? Icon(Icons.shield, color: Colors.white, size: 24 * safeSf) : null),
        SizedBox(height: 6 * safeSf),
        Text(name, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13 * safeSf), textAlign: TextAlign.center, overflow: TextOverflow.ellipsis, maxLines: 2),
      ],
    );
  }

  Widget _buildScoreCenter(BuildContext context, String id, double safeSf) {
    return Column(
      children: [
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            _scoreBox(myScore, Colors.green, safeSf),
            Text(" : ", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 22 * safeSf)),
            _scoreBox(opponentScore, Colors.grey, safeSf),
          ],
        ),
        SizedBox(height: 10 * safeSf),
        TextButton.icon(
          onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => PlacarPage(gameId: id, myTeam: myTeam, opponentTeam: opponentTeam))),
          icon: Icon(Icons.play_circle_fill, size: 18 * safeSf, color: const Color(0xFFE74C3C)),
          label: Text("RETORNAR", style: TextStyle(fontSize: 11 * safeSf, color: const Color(0xFFE74C3C), fontWeight: FontWeight.bold)),
          style: TextButton.styleFrom(backgroundColor: const Color(0xFFE74C3C).withOpacity(0.1), padding: EdgeInsets.symmetric(horizontal: 14 * safeSf, vertical: 8 * safeSf), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20 * safeSf)), visualDensity: VisualDensity.compact),
        ),
        SizedBox(height: 6 * safeSf),
        Text(status, style: TextStyle(fontSize: 12 * safeSf, color: Colors.blue, fontWeight: FontWeight.bold)),
      ],
    );
  }

  Widget _scoreBox(String pts, Color c, double safeSf) => Container(
    padding: EdgeInsets.symmetric(horizontal: 12 * safeSf, vertical: 6 * safeSf),
    decoration: BoxDecoration(color: c, borderRadius: BorderRadius.circular(8 * safeSf)),
    child: Text(pts, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16 * safeSf)),
  );
}

// --- POPUP DE CRIAÇÃO ---
class CreateGameDialogManual extends StatefulWidget {
  final TeamController teamController;
  final GameController gameController;

  const CreateGameDialogManual({super.key, required this.teamController, required this.gameController});

  @override
  State<CreateGameDialogManual> createState() => _CreateGameDialogManualState();
}

class _CreateGameDialogManualState extends State<CreateGameDialogManual> {
  late TextEditingController _seasonController;
  final TextEditingController _myTeamController = TextEditingController();
  final TextEditingController _opponentController = TextEditingController();
  bool _isLoading = false; 

  @override
  void initState() {
    super.initState();
    _seasonController = TextEditingController(text: _calculateSeason());
  }

  String _calculateSeason() {
    final now = DateTime.now();
    return now.month >= 7 ? "${now.year}/${(now.year + 1).toString().substring(2)}" : "${now.year - 1}/${now.year.toString().substring(2)}";
  }

  @override
  Widget build(BuildContext context) {
    final double safeSf = math.min(context.sf, 1.15); // TRAVÃO DO TABLET

    return AlertDialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20 * safeSf)),
      title: Text('Configurar Partida', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18 * safeSf)),
      content: SingleChildScrollView(
        child: Container(
          constraints: BoxConstraints(maxWidth: 450 * safeSf), // LIMITA A LARGURA NO TABLET
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(controller: _seasonController, style: TextStyle(fontSize: 14 * safeSf), decoration: InputDecoration(labelText: 'Temporada', labelStyle: TextStyle(fontSize: 14 * safeSf), border: const OutlineInputBorder(), prefixIcon: Icon(Icons.calendar_today, size: 20 * safeSf))),
              SizedBox(height: 15 * safeSf),
              _buildSearch(label: "Minha Equipa", controller: _myTeamController, safeSf: safeSf),
              Padding(padding: EdgeInsets.symmetric(vertical: 10 * safeSf), child: Text("VS", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 16 * safeSf))),
              _buildSearch(label: "Adversário", controller: _opponentController, safeSf: safeSf),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(onPressed: () => Navigator.pop(context), child: Text('CANCELAR', style: TextStyle(fontSize: 14 * safeSf))),
        ElevatedButton(
          style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFFE74C3C), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10 * safeSf)), padding: EdgeInsets.symmetric(horizontal: 16 * safeSf, vertical: 10 * safeSf)),
          onPressed: _isLoading ? null : () async {
            if (_myTeamController.text.isNotEmpty && _opponentController.text.isNotEmpty) {
              setState(() => _isLoading = true);
              String? newGameId = await widget.gameController.createGame(_myTeamController.text, _opponentController.text, _seasonController.text);
              setState(() => _isLoading = false);
              if (newGameId != null && context.mounted) {
                Navigator.pop(context);
                Navigator.push(context, MaterialPageRoute(builder: (context) => PlacarPage(gameId: newGameId, myTeam: _myTeamController.text, opponentTeam: _opponentController.text)));
              }
            }
          },
          child: _isLoading ? SizedBox(width: 20 * safeSf, height: 20 * safeSf, child: const CircularProgressIndicator(color: Colors.white, strokeWidth: 2)) : Text('CRIAR', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 14 * safeSf)),
        ),
      ],
    );
  }
  
  Widget _buildSearch({required String label, required TextEditingController controller, required double safeSf}) {
    return StreamBuilder<List<Map<String, dynamic>>>(
      stream: widget.teamController.teamsStream,
      builder: (context, snapshot) {
        List<Map<String, dynamic>> teamList = snapshot.hasData ? snapshot.data! : [];
        return Autocomplete<Map<String, dynamic>>(
          displayStringForOption: (Map<String, dynamic> option) => option['name'].toString(),
          optionsBuilder: (TextEditingValue val) {
            if (val.text.isEmpty) return const Iterable<Map<String, dynamic>>.empty();
            return teamList.where((t) => t['name'].toString().toLowerCase().contains(val.text.toLowerCase()));
          },
          onSelected: (Map<String, dynamic> selection) { controller.text = selection['name'].toString(); },
          optionsViewBuilder: (context, onSelected, options) {
            return Align(
              alignment: Alignment.topLeft,
              child: Material(
                elevation: 4.0, borderRadius: BorderRadius.circular(8 * safeSf),
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 250 * safeSf, maxWidth: 400 * safeSf), // Limita também o dropdown 
                  child: ListView.builder(
                    padding: EdgeInsets.zero, shrinkWrap: true, itemCount: options.length,
                    itemBuilder: (BuildContext context, int index) {
                      final option = options.elementAt(index);
                      final String name = option['name'].toString();
                      final String? imageUrl = option['image_url'];
                      return ListTile(
                        leading: CircleAvatar(radius: 20 * safeSf, backgroundColor: Colors.grey.shade200, backgroundImage: (imageUrl != null && imageUrl.isNotEmpty) ? NetworkImage(imageUrl) : null, child: (imageUrl == null || imageUrl.isEmpty) ? Icon(Icons.shield, color: Colors.grey, size: 20 * safeSf) : null),
                        title: Text(name, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14 * safeSf)),
                        onTap: () { onSelected(option); },
                      );
                    },
                  ),
                ),
              ),
            );
          },
          fieldViewBuilder: (ctx, txtCtrl, node, submit) {
            if (txtCtrl.text.isEmpty && controller.text.isNotEmpty) txtCtrl.text = controller.text;
            txtCtrl.addListener(() { controller.text = txtCtrl.text; });
            return TextField(
              controller: txtCtrl, focusNode: node, style: TextStyle(fontSize: 14 * safeSf),
              decoration: InputDecoration(labelText: label, labelStyle: TextStyle(fontSize: 14 * safeSf), prefixIcon: Icon(Icons.search, size: 20 * safeSf), border: const OutlineInputBorder()),
            );
          },
        );
      },
    );
  }
}

// (O RESTO DA CLASSE GamePage CONTINUA IGUAL, o sf nativo já estava protegido lá dentro)

// --- PÁGINA PRINCIPAL DOS JOGOS ---
class GamePage extends StatefulWidget {
  const GamePage({super.key});

  @override
  State<GamePage> createState() => _GamePageState();
}

class _GamePageState extends State<GamePage> {
  final GameController gameController = GameController();
  final TeamController teamController = TeamController();
  String selectedSeason = 'Todas';
  String selectedTeam = 'Todas';

  @override
  Widget build(BuildContext context) {
    bool isFilterActive = selectedSeason != 'Todas' || selectedTeam != 'Todas';

    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      appBar: AppBar(
        title: Text("Jogos", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20 * context.sf)),
        backgroundColor: Colors.white,
        elevation: 0,
        actions: [
          Padding(
            padding: EdgeInsets.only(right: 8.0 * context.sf),
            child: IconButton(
              icon: Icon(isFilterActive ? Icons.filter_list_alt : Icons.filter_list, color: isFilterActive ? const Color(0xFFE74C3C) : Colors.black87, size: 26 * context.sf),
              onPressed: () => _showFilterPopup(context),
            ),
          )
        ],
      ),
      body: StreamBuilder<List<Map<String, dynamic>>>(
        stream: teamController.teamsStream,
        builder: (context, teamSnapshot) {
          final List<Map<String, dynamic>> teamsList = teamSnapshot.data ?? [];
          return StreamBuilder<List<Game>>(
            stream: gameController.getFilteredGames(teamFilter: selectedTeam, seasonFilter: selectedSeason),
            builder: (context, gameSnapshot) {
              if (gameSnapshot.connectionState == ConnectionState.waiting && teamsList.isEmpty) return const Center(child: CircularProgressIndicator());
              if (gameSnapshot.hasError) return Center(child: Text("Erro: ${gameSnapshot.error}", style: TextStyle(fontSize: 14 * context.sf)));
              if (!gameSnapshot.hasData || gameSnapshot.data!.isEmpty) {
                return Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [Icon(Icons.search_off, size: 48 * context.sf, color: Colors.grey.shade300), SizedBox(height: 10 * context.sf), Text("Nenhum jogo encontrado.", style: TextStyle(fontSize: 14 * context.sf, color: Colors.grey.shade600))]));
              }
              return ListView.builder(
                padding: EdgeInsets.all(16 * context.sf),
                itemCount: gameSnapshot.data!.length,
                itemBuilder: (context, index) {
                  final game = gameSnapshot.data![index];
                  String? myLogo, oppLogo;
                  for (var team in teamsList) {
                    if (team['name'] == game.myTeam) myLogo = team['image_url'];
                    if (team['name'] == game.opponentTeam) oppLogo = team['image_url'];
                  }
                  return GameResultCard(
                    gameId: game.id, myTeam: game.myTeam, opponentTeam: game.opponentTeam, myScore: game.myScore,
                    opponentScore: game.opponentScore, status: game.status, season: game.season, myTeamLogo: myLogo, opponentTeamLogo: oppLogo, 
                  );
                },
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        heroTag: 'add_game_btn', // 👇 A MÁGICA ESTÁ AQUI TAMBÉM!
        backgroundColor: const Color(0xFFE74C3C),
        child: Icon(Icons.add, color: Colors.white, size: 24 * context.sf),
        onPressed: () => showDialog(context: context, builder: (context) => CreateGameDialogManual(teamController: teamController, gameController: gameController)),
      ),
    );
  }

  void _showFilterPopup(BuildContext context) {
    String tempSeason = selectedSeason;
    String tempTeam = selectedTeam;
    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setPopupState) {
            return AlertDialog(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20 * context.sf)),
              title: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('Filtrar Jogos', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18 * context.sf)),
                  IconButton(icon: const Icon(Icons.close, color: Colors.grey), onPressed: () => Navigator.pop(context), padding: EdgeInsets.zero, constraints: const BoxConstraints())
                ],
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("Temporada", style: TextStyle(fontSize: 12 * context.sf, color: Colors.grey.shade600, fontWeight: FontWeight.bold)),
                  SizedBox(height: 6 * context.sf),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 12 * context.sf), decoration: BoxDecoration(color: Colors.grey.shade100, borderRadius: BorderRadius.circular(10 * context.sf)),
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton<String>(
                        isExpanded: true, value: tempSeason, style: TextStyle(fontSize: 14 * context.sf, color: Colors.black87, fontWeight: FontWeight.bold),
                        items: ['Todas', '2024/25', '2025/26'].map((String value) => DropdownMenuItem<String>(value: value, child: Text(value))).toList(),
                        onChanged: (newValue) => setPopupState(() => tempSeason = newValue!),
                      ),
                    ),
                  ),
                  SizedBox(height: 20 * context.sf),
                  Text("Equipa", style: TextStyle(fontSize: 12 * context.sf, color: Colors.grey.shade600, fontWeight: FontWeight.bold)),
                  SizedBox(height: 6 * context.sf),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 12 * context.sf), decoration: BoxDecoration(color: Colors.grey.shade100, borderRadius: BorderRadius.circular(10 * context.sf)),
                    child: StreamBuilder<List<Map<String, dynamic>>>(
                      stream: teamController.teamsStream,
                      builder: (context, snapshot) {
                        List<String> teamNames = ['Todas'];
                        if (snapshot.hasData) teamNames.addAll(snapshot.data!.map((t) => t['name'].toString()));
                        if (!teamNames.contains(tempTeam)) tempTeam = 'Todas';
                        return DropdownButtonHideUnderline(
                          child: DropdownButton<String>(
                            isExpanded: true, value: tempTeam, style: TextStyle(fontSize: 14 * context.sf, color: Colors.black87, fontWeight: FontWeight.bold),
                            items: teamNames.map((String value) => DropdownMenuItem<String>(value: value, child: Text(value, overflow: TextOverflow.ellipsis))).toList(),
                            onChanged: (newValue) => setPopupState(() => tempTeam = newValue!),
                          ),
                        );
                      }
                    ),
                  ),
                ],
              ),
              actions: [
                TextButton(onPressed: () { setState(() { selectedSeason = 'Todas'; selectedTeam = 'Todas'; }); Navigator.pop(context); }, child: Text('LIMPAR', style: TextStyle(fontSize: 12 * context.sf, color: Colors.grey))),
                ElevatedButton(style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFFE74C3C), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10 * context.sf))), onPressed: () { setState(() { selectedSeason = tempSeason; selectedTeam = tempTeam; }); Navigator.pop(context); }, child: Text('APLICAR', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 13 * context.sf))),
              ],
            );
          }
        );
      },
    );
  }
}