import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math' as math;

import '../utils/size_extension.dart';
import '../classe/theme.dart'; 
import '../controllers/placar_controller.dart'; 
import '../widgets/placar_widgets.dart'; 

class PlacarPage extends StatefulWidget {
  final String gameId, myTeam, opponentTeam;
  
  const PlacarPage({
    super.key, 
    required this.gameId, 
    required this.myTeam, 
    required this.opponentTeam
  });

  @override
  State<PlacarPage> createState() => _PlacarPageState();
}

class _PlacarPageState extends State<PlacarPage> {
  late PlacarController _controller;

  @override
  void initState() {
    super.initState();
    // Força o ecrã deitado
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeRight,
      DeviceOrientation.landscapeLeft,
    ]);
    
    // 👇 Inicia o controlador SEM o callback onUpdate (o AnimatedBuilder resolve isso)
    _controller = PlacarController(
      gameId: widget.gameId,
      myTeam: widget.myTeam, 
      opponentTeam: widget.opponentTeam,
    );
    _controller.loadPlayers();
  }

  @override
  void dispose() {
    // 👇 Importante limpar o controller para parar timers em background
    _controller.dispose();
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    super.dispose();
  }

  // Helper para botões de falta (Draggable)
  Widget _buildFloatingFoulBtn(String label, Color color, String action, IconData icon, double left, double right, double top, double sf) {
    return Positioned(
      top: top,
      left: left > 0 ? left : null,
      right: right > 0 ? right : null,
      child: Draggable<String>(
        data: action,
        feedback: Material(
          color: Colors.transparent,
          child: CircleAvatar(
            radius: 30 * sf, 
            backgroundColor: color.withOpacity(0.8), 
            child: Icon(icon, color: Colors.white, size: 30 * sf) 
          ),
        ),
        child: Column(
          children: [
            CircleAvatar(
              radius: 27 * sf, 
              backgroundColor: color,
              child: Icon(icon, color: Colors.white, size: 28 * sf), 
            ),
            SizedBox(height: 5 * sf), 
            Text(label, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12 * sf)), 
          ],
        ),
      ),
    );
  }

  // Helper para botões de canto
  Widget _buildCornerBtn({required String heroTag, required IconData icon, required Color color, required VoidCallback? onTap, required double size, bool isLoading = false}) {
    return SizedBox(
      width: size, 
      height: size,
      child: FloatingActionButton(
        heroTag: heroTag, 
        backgroundColor: onTap == null ? Colors.grey : color,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14 * (size / 50))), 
        elevation: 5, 
        onPressed: isLoading ? null : onTap,
        child: isLoading 
            ? SizedBox(width: size * 0.45, height: size * 0.45, child: const CircularProgressIndicator(color: Colors.white, strokeWidth: 2.5)) 
            : Icon(icon, color: Colors.white, size: size * 0.55), 
      ),
    );
  }

  void _showHeatmap(BuildContext context) {
    Map<String, Map<String, int>> statsByNames = {};
    _controller.playerStats.forEach((id, stats) {
      String nomeDoJogador = _controller.playerNames[id] ?? 'Desconhecido';
      statsByNames[nomeDoJogador] = stats;
    });

    showDialog(
      context: context,
      builder: (ctx) => HeatmapDialog(
        shots: _controller.matchShots,
        myTeamName: _controller.myTeam,
        oppTeamName: _controller.opponentTeam,
        myPlayers: [..._controller.myCourt, ..._controller.myBench].map((id) => _controller.playerNames[id]!).toList(),
        oppPlayers: [..._controller.oppCourt, ..._controller.oppBench].map((id) => _controller.playerNames[id]!).toList(),
        playerStats: statsByNames, 
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final double wScreen = MediaQuery.of(context).size.width;
    final double hScreen = MediaQuery.of(context).size.height;
    final double sf = math.min(wScreen / 1150, hScreen / 720); 
    final double cornerBtnSize = 48 * sf; 

    // 👇 O AnimatedBuilder ouve o controller e redesenha o necessário de forma eficiente
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        if (_controller.isLoading) {
          return Scaffold(
            backgroundColor: AppTheme.placarDarkSurface, 
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("PREPARANDO O PAVILHÃO", style: TextStyle(color: Colors.white24, fontSize: 45 * sf, fontWeight: FontWeight.bold, letterSpacing: 2)), 
                  SizedBox(height: 35 * sf), 
                  const CircularProgressIndicator(color: Colors.orangeAccent),
                ],
              ),
            ),
          );
        }

        return Scaffold(
          backgroundColor: AppTheme.placarBackground, 
          body: SafeArea(
            top: false, bottom: false, 
            child: IgnorePointer(
              ignoring: _controller.isSaving, 
              child: Stack(
                children: [
                  // --- ÁREA DO CAMPO ---
                  Container(
                    margin: EdgeInsets.only(left: 65 * sf, right: 65 * sf, bottom: 55 * sf), 
                    decoration: BoxDecoration(border: Border.all(color: Colors.white, width: 2.5)), 
                    child: LayoutBuilder(
                      builder: (context, constraints) {
                        final w = constraints.maxWidth;
                        final h = constraints.maxHeight;

                        return Stack(
                          children: [
                            GestureDetector(
                              onTapDown: (details) {
                                if (_controller.isSelectingShotLocation) {
                                  _controller.registerShotLocation(context, details.localPosition, Size(w, h));
                                }
                              },
                              child: Container(
                                decoration: const BoxDecoration(
                                  image: DecorationImage(
                                    image: AssetImage('assets/campo.png'), 
                                    fit: BoxFit.fill, 
                                  ),                                           
                                ),
                              ),
                            ),

                            // JOGADORES EM CAMPO
                            if (!_controller.isSelectingShotLocation && _controller.myCourt.length >= 5 && _controller.oppCourt.length >= 5) ...[
                              Positioned(top: h * 0.25, left: w * 0.02, child: PlayerCourtCard(controller: _controller, playerId: _controller.myCourt[0], isOpponent: false, sf: sf)),
                              Positioned(top: h * 0.68, left: w * 0.02, child: PlayerCourtCard(controller: _controller, playerId: _controller.myCourt[1], isOpponent: false, sf: sf)),
                              Positioned(top: h * 0.45, left: w * 0.25, child: PlayerCourtCard(controller: _controller, playerId: _controller.myCourt[2], isOpponent: false, sf: sf)),
                              Positioned(top: h * 0.15, left: w * 0.20, child: PlayerCourtCard(controller: _controller, playerId: _controller.myCourt[3], isOpponent: false, sf: sf)),
                              Positioned(top: h * 0.80, left: w * 0.20, child: PlayerCourtCard(controller: _controller, playerId: _controller.myCourt[4], isOpponent: false, sf: sf)),
                              
                              Positioned(top: h * 0.25, right: w * 0.02, child: PlayerCourtCard(controller: _controller, playerId: _controller.oppCourt[0], isOpponent: true, sf: sf)), 
                              Positioned(top: h * 0.68, right: w * 0.02, child: PlayerCourtCard(controller: _controller, playerId: _controller.oppCourt[1], isOpponent: true, sf: sf)), 
                              Positioned(top: h * 0.45, right: w * 0.25, child: PlayerCourtCard(controller: _controller, playerId: _controller.oppCourt[2], isOpponent: true, sf: sf)), 
                              Positioned(top: h * 0.15, right: w * 0.20, child: PlayerCourtCard(controller: _controller, playerId: _controller.oppCourt[3], isOpponent: true, sf: sf)), 
                              Positioned(top: h * 0.80, right: w * 0.20, child: PlayerCourtCard(controller: _controller, playerId: _controller.oppCourt[4], isOpponent: true, sf: sf)), 
                            ],

                            // BOTÕES DE FALTA RÁPIDA
                            if (!_controller.isSelectingShotLocation) ...[
                              _buildFloatingFoulBtn("FALTA +", AppTheme.actionPoints, "add_foul", Icons.sports, w * 0.39, 0.0, h * 0.31, sf), 
                              _buildFloatingFoulBtn("FALTA -", AppTheme.actionMiss, "sub_foul", Icons.block, 0.0, w * 0.39, h * 0.31, sf), 
                            ],

                            // CRONÓMETRO CENTRAL / PLAY-PAUSE
                            if (!_controller.isSelectingShotLocation)
                              Positioned(
                                top: (h * 0.32) + (40 * sf), 
                                left: 0, right: 0, 
                                child: Center(
                                  child: GestureDetector(
                                    onTap: () => _controller.toggleTimer(context),
                                    child: CircleAvatar(
                                      radius: 68 * sf, 
                                      backgroundColor: Colors.grey.withOpacity(0.5), 
                                      child: Icon(_controller.isRunning ? Icons.pause : Icons.play_arrow, color: Colors.white, size: 58 * sf)
                                    ), 
                                  ),
                                ),
                              ),

                            Positioned(top: 0, left: 0, right: 0, child: Center(child: TopScoreboard(controller: _controller, sf: sf))),
                            
                            if (!_controller.isSelectingShotLocation) Positioned(bottom: -10 * sf, left: 0, right: 0, child: ActionButtonsPanel(controller: _controller, sf: sf)),

                            if (_controller.isSelectingShotLocation)
                              Positioned(
                                top: h * 0.4, left: 0, right: 0,
                                child: Center(
                                  child: Container(
                                    padding: EdgeInsets.symmetric(horizontal: 35 * sf, vertical: 18 * sf), 
                                    decoration: BoxDecoration(color: Colors.black87, borderRadius: BorderRadius.circular(11 * sf), border: Border.all(color: Colors.white, width: 1.5 * sf)), 
                                    child: Text("TOQUE NO CAMPO PARA MARCAR O LOCAL", style: TextStyle(color: Colors.white, fontSize: 22 * sf, fontWeight: FontWeight.bold)), 
                                  ),
                                ),
                              ),
                          ],
                        );
                      },
                    ),
                  ),

                  // BOTÕES LATERAIS (SAVE & HEATMAP)
                  Positioned(
                    top: 50 * sf, left: 12 * sf, 
                    child: _buildCornerBtn(
                      heroTag: 'btn_save_exit', icon: Icons.save_alt, color: AppTheme.oppTeamRed, size: cornerBtnSize, isLoading: _controller.isSaving, 
                      onTap: () async {
                        await _controller.saveGameStats(context);
                        if (context.mounted) Navigator.pop(context);
                      }
                    ),
                  ),
                  Positioned(
                    top: 50 * sf, right: 12 * sf, 
                    child: _buildCornerBtn(heroTag: 'btn_heatmap', icon: Icons.local_fire_department, color: Colors.orange.shade800, size: cornerBtnSize, onTap: () => _showHeatmap(context)),
                  ),

                  // CONTROLOS EQUIPA CASA (ESQUERDA)
                  Positioned(
                    bottom: 55 * sf, left: 12 * sf, 
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        if (_controller.showMyBench) BenchPlayersList(controller: _controller, isOpponent: false, sf: sf),
                        SizedBox(height: 12 * sf), 
                        _buildCornerBtn(heroTag: 'btn_sub_home', icon: Icons.swap_horiz, color: AppTheme.myTeamBlue, size: cornerBtnSize, onTap: () { _controller.showMyBench = !_controller.showMyBench; _controller.notifyListeners(); }),
                        SizedBox(height: 12 * sf), 
                        _buildCornerBtn(
                          heroTag: 'btn_to_home', 
                          icon: Icons.timer, 
                          color: AppTheme.myTeamBlue, 
                          size: cornerBtnSize, 
                          onTap: _controller.myTimeoutsUsed >= 3 ? null : () => _controller.useTimeout(false)
                        ),
                      ],
                    ),
                  ),

                  // CONTROLOS EQUIPA VISITANTE (DIREITA)
                  Positioned(
                    bottom: 55 * sf, right: 12 * sf, 
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        if (_controller.showOppBench) BenchPlayersList(controller: _controller, isOpponent: true, sf: sf),
                        SizedBox(height: 12 * sf), 
                        _buildCornerBtn(heroTag: 'btn_sub_away', icon: Icons.swap_horiz, color: AppTheme.oppTeamRed, size: cornerBtnSize, onTap: () { _controller.showOppBench = !_controller.showOppBench; _controller.notifyListeners(); }), 
                        SizedBox(height: 12 * sf), 
                        _buildCornerBtn(
                          heroTag: 'btn_to_away', 
                          icon: Icons.timer, 
                          color: AppTheme.oppTeamRed, 
                          size: cornerBtnSize, 
                          onTap: _controller.opponentTimeoutsUsed >= 3 ? null : () => _controller.useTimeout(true)
                        ),
                      ],
                    ),
                  ),

                  // OVERLAY DE GRAVAÇÃO
                  if (_controller.isSaving)
                    Positioned.fill(child: Container(color: Colors.black.withOpacity(0.4), child: const Center(child: CircularProgressIndicator(color: Colors.white)))),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}