  import 'package:flutter/material.dart';
  import 'package:flutter/services.dart';
  import 'package:playmaker/controllers/placar_controller.dart';
import 'package:playmaker/utils/size_extension.dart';
  import 'package:playmaker/widgets/placar_widgets.dart';
  import 'dart:math' as math;

  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();
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.landscapeRight,
        DeviceOrientation.landscapeLeft,
      ]);
      
      _controller = PlacarController(
        gameId: widget.gameId,
        myTeam: widget.myTeam, 
        opponentTeam: widget.opponentTeam,
        onUpdate: () {
          if (mounted) setState(() {});
        }
      );
      _controller.loadPlayers();
    }

    @override
    void dispose() {
      _controller.dispose();
      SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
      super.dispose();
    }

    // --- BOTÕES FLUTUANTES DE FALTA ---
    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)), 
            ],
          ),
        ),
      );
    }

    // --- BOTÕES LATERAIS QUADRADOS ---
    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: 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), 
        ),
      );
    }

    @override
    Widget build(BuildContext context) {
      final double wScreen = MediaQuery.of(context).size.width;
      final double hScreen = MediaQuery.of(context).size.height;
      
      // 👇 CÁLCULO MANUAL DO SF 👇
      final double sf = math.min(wScreen / 1150, hScreen / 720); 

      final double cornerBtnSize = 48 * sf; // Tamanho ideal (Nem 38 nem 55)

      if (_controller.isLoading) {
        return Scaffold(
          backgroundColor: const Color(0xFF16202C),
          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), 
                StreamBuilder(
                  stream: Stream.periodic(const Duration(seconds: 3)),
                  builder: (context, snapshot) {
                    List<String> frases = [
                      "O Treinador está a desenhar a tática...",
                      "A encher as bolas com ar de campeão...",
                      "O árbitro está a testar o apito...",
                      "A verificar se o cesto está nivelado...",
                      "Os jogadores estão a terminar o aquecimento..."
                    ];
                    String frase = frases[DateTime.now().second % frases.length];
                    return Text(frase, style: TextStyle(color: Colors.orange.withOpacity(0.7), fontSize: 26 * sf, fontStyle: FontStyle.italic)); 
                  },
                ),
              ],
            ),
          ),
        );
      }

      return Scaffold(
        backgroundColor: const Color(0xFF266174),
        body: SafeArea(
          top: false,    
          bottom: false, 
          // 👇 A MÁGICA DO IGNORE POINTER COMEÇA AQUI 👇
          child: IgnorePointer(
            ignoring: _controller.isSaving, // Se estiver a gravar, ignora os toques!
            child: Stack(
              children: [
                // --- O 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, 
                                ),                          
                              ),
child: Stack(
                            children: _controller.matchShots.map((shot) => Positioned(
                              // Agora usamos relativeX e relativeY multiplicados pela largura(w) e altura(h)
                              left: (shot.relativeX * w) - (9 * context.sf), 
                              top: (shot.relativeY * h) - (9 * context.sf), 
                              child: CircleAvatar(
                                radius: 9 * context.sf, 
                                backgroundColor: shot.isMake ? Colors.green : Colors.red, 
                                child: Icon(shot.isMake ? Icons.check : Icons.close, size: 11 * context.sf, color: Colors.white)
                              ), 
                            )).toList(),
                          ),
                            ),
                          ),

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

                          // --- BOTÕES DE FALTAS ---
                          if (!_controller.isSelectingShotLocation) ...[
                            _buildFloatingFoulBtn("FALTA +", Colors.orange, "add_foul", Icons.sports, w * 0.39, 0.0, h * 0.31, sf),
                            _buildFloatingFoulBtn("FALTA -", Colors.redAccent, "sub_foul", Icons.block, 0.0, w * 0.39, h * 0.31, sf),
                          ],

                          // --- BOTÃO 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)
                                  ), 
                                ),
                              ),
                            ),
                          // --- PLACAR NO TOPO ---
                          Positioned(top: 0, left: 0, right: 0, child: Center(child: TopScoreboard(controller: _controller, sf: sf))),
                          
                          // --- BOTÕES DE AÇÃO ---
                          if (!_controller.isSelectingShotLocation) Positioned(bottom: -10 * sf, left: 0, right: 0, child: ActionButtonsPanel(controller: _controller, sf: sf)),

                          // --- OVERLAY LANÇAMENTO ---
                          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 DO LANÇAMENTO", style: TextStyle(color: Colors.white, fontSize: 27 * sf, fontWeight: FontWeight.bold)), 
                                ),
                              ),
                            ),
                        ],
                      );
                    },
                  ),
                ),

                // --- BOTÕES LATERAIS ---
                // Topo Esquerdo: Guardar e Sair (Botão Único)
                Positioned(
                  top: 50 * sf, left: 12 * sf, 
                  child: _buildCornerBtn(
                    heroTag: 'btn_save_exit', 
                    icon: Icons.save_alt, 
                    color: const Color(0xFFD92C2C), 
                    size: cornerBtnSize, 
                    isLoading: _controller.isSaving, 
                    onTap: () async {
                      // 1. Primeiro obriga a guardar os dados na BD
                      await _controller.saveGameStats(context);
                      
                      // 2. Só depois de acabar de guardar é que volta para trás
                      if (context.mounted) {
                        Navigator.pop(context);
                      }
                    }
                  ),
                ),

                // Base Esquerda: Banco Casa + TIMEOUT DA CASA
                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: const Color(0xFF1E5BB2), size: cornerBtnSize, onTap: () { _controller.showMyBench = !_controller.showMyBench; _controller.onUpdate(); }),
                      SizedBox(height: 12 * sf), 
                      _buildCornerBtn(
                        heroTag: 'btn_to_home', 
                        icon: Icons.timer, 
                        color: _controller.myTimeoutsUsed >= 3 ? Colors.grey : const Color(0xFF1E5BB2), 
                        size: cornerBtnSize, 
                        onTap: _controller.myTimeoutsUsed >= 3 
                          ? () => ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('🛑 A equipa da casa já usou os 3 Timeouts deste período!'), backgroundColor: Colors.red))
                          : () => _controller.useTimeout(false)
                      ),
                    ],
                  ),
                ),

                // Base Direita: Banco Visitante + TIMEOUT DO VISITANTE
                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: const Color(0xFFD92C2C), size: cornerBtnSize, onTap: () { _controller.showOppBench = !_controller.showOppBench; _controller.onUpdate(); }),
                      SizedBox(height: 12 * sf), 
                      _buildCornerBtn(
                        heroTag: 'btn_to_away', 
                        icon: Icons.timer, 
                        color: _controller.opponentTimeoutsUsed >= 3 ? Colors.grey : const Color(0xFFD92C2C), 
                        size: cornerBtnSize, 
                        onTap: _controller.opponentTimeoutsUsed >= 3 
                          ? () => ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('🛑 A equipa visitante já usou os 3 Timeouts deste período!'), backgroundColor: Colors.red))
                          : () => _controller.useTimeout(true)
                      ),
                    ],
                  ),
                ),

                // 👇 EFEITO VISUAL (Ecrã escurece para mostrar que está a carregar) 👇
                if (_controller.isSaving)
                  Positioned.fill(
                    child: Container(
                      color: Colors.black.withOpacity(0.4), 
                    ),
                  ),

              ],
            ),
          ),
        ),
      );
    }
  }