import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:playmaker/controllers/placar_controller.dart';
import 'package:playmaker/pages/heatmap_page.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();
  }

  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)), 
          ],
        ),
      ),
    );
  }

  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;
    
    // Calcula o tamanho normal
    double sf = math.min(wScreen / 1150, hScreen / 720); 
    
    // 👇 O TRAVÃO DE MÃO PARA OS TABLETS 👇
    sf = math.min(sf, 0.9);     
    final double cornerBtnSize = 48 * sf;

    if (_controller.isLoading) {
      return Scaffold(backgroundColor: const Color(0xFF16202C), body: Center(child: Text("PREPARANDO O PAVILHÃO...", style: TextStyle(color: Colors.white24, fontSize: 45 * sf, fontWeight: FontWeight.bold))));
    }

    return Scaffold(
      backgroundColor: const Color(0xFF266174),
      body: SafeArea(
        top: false, bottom: false, 
        child: IgnorePointer(
          ignoring: _controller.isSaving, 
          child: Stack(
            children: [
              // ==========================================
              // --- 1. 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),
                  image: const DecorationImage(image: AssetImage('assets/campo.png'), fit: BoxFit.fill),                          
                ),
                child: LayoutBuilder(
                  builder: (context, constraints) {
                    final w = constraints.maxWidth;
                    final h = constraints.maxHeight;

                    return Stack(
                      children: [
                        Positioned.fill(
                          child: GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTapDown: (details) {
                              if (_controller.isSelectingShotLocation) {
                                _controller.registerShotLocation(context, details.localPosition, Size(w, h));
                              }
                            },
                            child: Stack(
                              children: _controller.matchShots.map((shot) => Positioned(
                                left: (shot.relativeX * w) - (9 * sf), 
                                top: (shot.relativeY * h) - (9 * sf), 
                                child: CircleAvatar(radius: 9 * sf, backgroundColor: shot.isMake ? Colors.green : Colors.red, child: Icon(shot.isMake ? Icons.check : Icons.close, size: 11 * 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.36) + (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))),
                      ],
                    );
                  },
                ),
              ),

              // ==========================================
              // --- 2. O RODAPÉ (BOTÕES DE JOGO) ---
              // ==========================================
              if (!_controller.isSelectingShotLocation) 
                Positioned(
                  bottom: 60 * sf, 
                  left: 0, 
                  right: 0, 
                  child: ActionButtonsPanel(controller: _controller, sf: sf)
                ),

              // ==========================================
              // --- 3. BOTÕES LATERAIS ---
              // ==========================================
              
              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 { await _controller.saveGameStats(context); if (context.mounted) Navigator.pop(context); })),

              Positioned(top: 50 * sf, right: 12 * sf, child: _buildCornerBtn(heroTag: 'btn_heatmap', icon: Icons.analytics_outlined, color: Colors.purple.shade700, size: cornerBtnSize, onTap: () { if (_controller.matchShots.isEmpty) { ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Ainda não há lançamentos!'))); return; } Navigator.push(context, MaterialPageRoute(builder: (context) => HeatmapPage(shots: _controller.matchShots, teamName: _controller.myTeam))); })),

              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('🛑 Esgotado!'), backgroundColor: Colors.red)) : () => _controller.useTimeout(false))])),
              
              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('🛑 Esgotado!'), backgroundColor: Colors.red)) : () => _controller.useTimeout(true))])),

              if (_controller.isSaving) Positioned.fill(child: Container(color: Colors.black.withOpacity(0.4))),
            ],
          ),
        ),
      ),
    );
  }
}

// ==============================================================
// 🏀 WIDGETS AUXILIARES (TopScoreboard, ActionButtonsPanel, etc)
// ==============================================================
class TopScoreboard extends StatelessWidget {
  final PlacarController controller;
  final double sf;
  const TopScoreboard({super.key, required this.controller, required this.sf});
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 10 * sf, horizontal: 35 * sf),
      decoration: BoxDecoration(color: const Color(0xFF16202C), borderRadius: BorderRadius.only(bottomLeft: Radius.circular(22 * sf), bottomRight: Radius.circular(22 * sf)), border: Border.all(color: Colors.white, width: 2.5 * sf)),
      child: Row(
        mainAxisSize: MainAxisSize.min, 
        children: [
          _buildTeamSection(controller.myTeam, controller.myScore, controller.myFouls, controller.myTimeoutsUsed, const Color(0xFF1E5BB2), false, sf),
          SizedBox(width: 30 * sf),
          Column(mainAxisSize: MainAxisSize.min, children: [Container(padding: EdgeInsets.symmetric(horizontal: 18 * sf, vertical: 5 * sf), decoration: BoxDecoration(color: const Color(0xFF2C3E50), borderRadius: BorderRadius.circular(9 * sf)), child: Text(controller.formatTime(), style: TextStyle(color: Colors.white, fontSize: 28 * sf, fontWeight: FontWeight.w900, fontFamily: 'monospace', letterSpacing: 2 * sf))), SizedBox(height: 5 * sf), Text("PERÍODO ${controller.currentQuarter}", style: TextStyle(color: Colors.orangeAccent, fontSize: 14 * sf, fontWeight: FontWeight.w900))]),
          SizedBox(width: 30 * sf),
          _buildTeamSection(controller.opponentTeam, controller.opponentScore, controller.opponentFouls, controller.opponentTimeoutsUsed, const Color(0xFFD92C2C), true, sf),
        ],
      ),
    );
  }
  Widget _buildTeamSection(String name, int score, int fouls, int timeouts, Color color, bool isOpp, double sf) {
    int displayFouls = fouls > 5 ? 5 : fouls;
    final timeoutIndicators = Row(mainAxisSize: MainAxisSize.min, children: List.generate(3, (index) => Container(margin: EdgeInsets.symmetric(horizontal: 3.5 * sf), width: 12 * sf, height: 12 * sf, decoration: BoxDecoration(shape: BoxShape.circle, color: index < timeouts ? Colors.yellow : Colors.grey.shade600, border: Border.all(color: Colors.white54, width: 1.5 * sf)))));
    List<Widget> content = [Column(children: [_scoreBox(score, color, sf), SizedBox(height: 7 * sf), timeoutIndicators]), SizedBox(width: 18 * sf), Column(crossAxisAlignment: isOpp ? CrossAxisAlignment.start : CrossAxisAlignment.end, children: [Text(name.toUpperCase(), style: TextStyle(color: Colors.white, fontSize: 20 * sf, fontWeight: FontWeight.w900, letterSpacing: 1.2 * sf)), SizedBox(height: 5 * sf), Text("FALTAS: $displayFouls", style: TextStyle(color: displayFouls >= 5 ? Colors.redAccent : Colors.yellowAccent, fontSize: 13 * sf, fontWeight: FontWeight.bold))])];
    return Row(crossAxisAlignment: CrossAxisAlignment.center, children: isOpp ? content : content.reversed.toList());
  }
  Widget _scoreBox(int score, Color color, double sf) => Container(width: 58 * sf, height: 45 * sf, alignment: Alignment.center, decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(7 * sf)), child: Text(score.toString(), style: TextStyle(color: Colors.white, fontSize: 26 * sf, fontWeight: FontWeight.w900)));
}

class BenchPlayersList extends StatelessWidget {
  final PlacarController controller;
  final bool isOpponent;
  final double sf;
  const BenchPlayersList({super.key, required this.controller, required this.isOpponent, required this.sf});
  @override
  Widget build(BuildContext context) {
    final bench = isOpponent ? controller.oppBench : controller.myBench;
    final teamColor = isOpponent ? const Color(0xFFD92C2C) : const Color(0xFF1E5BB2);
    final prefix = isOpponent ? "bench_opp_" : "bench_my_";
    return Column(mainAxisSize: MainAxisSize.min, children: bench.map((playerName) {
        final num = controller.playerNumbers[playerName] ?? "0";
        final bool isFouledOut = (controller.playerStats[playerName]?["fls"] ?? 0) >= 5; 
        Widget avatarUI = Container(margin: EdgeInsets.only(bottom: 7 * sf), decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: Colors.white, width: 1.8 * sf), boxShadow: [BoxShadow(color: Colors.black45, blurRadius: 5 * sf, offset: Offset(0, 2.5 * sf))]), child: CircleAvatar(radius: 22 * sf, backgroundColor: isFouledOut ? Colors.grey.shade800 : teamColor, child: Text(num, style: TextStyle(color: isFouledOut ? Colors.red.shade300 : Colors.white, fontSize: 16 * sf, fontWeight: FontWeight.bold, decoration: isFouledOut ? TextDecoration.lineThrough : TextDecoration.none))));
        if (isFouledOut) return GestureDetector(onTap: () => ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('🛑 $playerName não pode voltar (Expulso).'), backgroundColor: Colors.red)), child: avatarUI);
        return Draggable<String>(data: "$prefix$playerName", feedback: Material(color: Colors.transparent, child: CircleAvatar(radius: 28 * sf, backgroundColor: teamColor, child: Text(num, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18 * sf)))), childWhenDragging: Opacity(opacity: 0.5, child: SizedBox(width: 45 * sf, height: 45 * sf)), child: avatarUI);
      }).toList());
  }
}

class PlayerCourtCard extends StatelessWidget {
  final PlacarController controller;
  final String name;
  final bool isOpponent;
  final double sf;
  const PlayerCourtCard({super.key, required this.controller, required this.name, required this.isOpponent, required this.sf});

  @override
  Widget build(BuildContext context) {
    final teamColor = isOpponent ? const Color(0xFFD92C2C) : const Color(0xFF1E5BB2);
    final stats = controller.playerStats[name]!;
    final number = controller.playerNumbers[name]!;
    final prefix = isOpponent ? "player_opp_" : "player_my_";
    final int fouls = stats["fls"] ?? 0;

    return Draggable<String>(
      data: "$prefix$name",
      feedback: Material(color: Colors.transparent, child: Container(padding: EdgeInsets.symmetric(horizontal: 18 * sf, vertical: 11 * sf), decoration: BoxDecoration(color: teamColor.withOpacity(0.9), borderRadius: BorderRadius.circular(9 * sf)), child: Text(name, style: TextStyle(color: Colors.white, fontSize: 20 * sf, fontWeight: FontWeight.bold)))),
      childWhenDragging: Opacity(opacity: 0.5, child: _playerCardUI(context, number, name, stats, teamColor, false, false, sf, fouls)),
      child: DragTarget<String>(
        onAcceptWithDetails: (details) {
          final action = details.data;
          if (action.startsWith("add_") || action.startsWith("sub_") || action.startsWith("miss_")) controller.handleActionDrag(context, action, "$prefix$name");
          else if (action.startsWith("bench_")) controller.handleSubbing(context, action, name, isOpponent);
        },
        builder: (context, candidateData, rejectedData) => _playerCardUI(
            context,
            number,
            name,
            stats,
            teamColor,
            candidateData.any((d) => d != null && d.startsWith("bench_")),
            candidateData.any((d) => d != null && (d.startsWith("add_") || d.startsWith("sub_") || d.startsWith("miss_"))),
            sf,
            fouls),
      ),
    );
  }

  Widget _playerCardUI(BuildContext context, String number, String name, Map<String, int> stats, Color teamColor, bool isSubbing, bool isActionHover, double sf, int fouls) {
    bool isFouledOut = fouls >= 5;
    Color bgColor = isFouledOut ? Colors.red.shade50 : (isSubbing ? Colors.blue.shade50 : (isActionHover ? Colors.orange.shade50 : Colors.white));
    Color borderColor = isFouledOut ? Colors.redAccent : (isSubbing ? Colors.blue : (isActionHover ? Colors.orange : Colors.transparent));
    
    int fgm = stats["fgm"]!; int fga = stats["fga"]!; 
    String fgPercent = fga > 0 ? ((fgm / fga) * 100).toStringAsFixed(0) : "0";
    String displayName = name.length > 12 ? "${name.substring(0, 10)}..." : name;

    return GestureDetector(
      onTap: () {
        final playerShots = controller.matchShots.where((s) => s.playerName == name).toList();
        if (playerShots.isEmpty) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('O $name ainda não lançou!')));
          return;
        }
        Navigator.push(context, MaterialPageRoute(builder: (context) => HeatmapPage(shots: playerShots, teamName: name)));
      },
      child: Container(
        decoration: BoxDecoration(
          color: bgColor,
          borderRadius: BorderRadius.circular(11 * sf),
          border: Border.all(color: borderColor, width: 2 * sf),
          boxShadow: [BoxShadow(color: Colors.black26, blurRadius: 5 * sf, offset: Offset(2 * sf, 3.5 * sf))]
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(9 * sf),
          child: IntrinsicHeight(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                // --- LADO ESQUERDO: APENAS O NÚMERO ---
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 16 * sf),
                  color: isFouledOut ? Colors.grey[700] : teamColor,
                  alignment: Alignment.center,
                  child: Text(number, style: TextStyle(color: Colors.white, fontSize: 24 * sf, fontWeight: FontWeight.bold)),
                ),
                // --- LADO DIREITO: INFO ---
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 12 * sf, vertical: 7 * sf),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(displayName, style: TextStyle(fontSize: 16 * sf, fontWeight: FontWeight.bold, color: isFouledOut ? Colors.red : Colors.black87, decoration: isFouledOut ? TextDecoration.lineThrough : TextDecoration.none)),
                      SizedBox(height: 2 * sf),
                      Text("${stats["pts"]} Pts | FG: $fgm/$fga ($fgPercent%)", style: TextStyle(fontSize: 12 * sf, color: isFouledOut ? Colors.red : Colors.grey[700], fontWeight: FontWeight.bold)),
                      // Texto de faltas com destaque se estiver em perigo (4 ou 5)
                      Text("AST: ${stats["ast"]} | REB: ${stats["orb"]! + stats["drb"]!} | FALTAS: $fouls", 
                        style: TextStyle(
                          fontSize: 11 * sf, 
                          color: fouls >= 4 ? Colors.red : Colors.grey[600], 
                          fontWeight: fouls >= 4 ? FontWeight.w900 : FontWeight.w600
                        )),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
