import 'package:flutter/material.dart';
import 'package:playmaker/classe/theme.dart';
import 'package:playmaker/controllers/placar_controller.dart';

// ============================================================================
// 4. PAINEL DE BOTÕES DE ACÇÃO (DRAG & DROP)
// ============================================================================
class ActionButtonsPanel extends StatelessWidget {
  final PlacarController controller;
  final double sf;

  const ActionButtonsPanel({super.key, required this.controller, required this.sf});

  @override
  Widget build(BuildContext context) {
    final double baseSize = 58 * sf;
    final double feedSize = 73 * sf;
    final double gap = 5 * sf;

    return Padding(
      padding: EdgeInsets.only(bottom: 12 * sf),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          _columnBtn([
            _dragAndTargetBtn("-1", AppTheme.actionMiss,    "miss_1",    baseSize, feedSize, sf, badge: ""),
            _dragAndTargetBtn("1",  AppTheme.actionPoints,  "add_pts_1", baseSize, feedSize, sf, badge: "FTM"),
            _dragAndTargetBtn("1",  AppTheme.actionPoints,  "sub_pts_1", baseSize, feedSize, sf, badge: "FTA", isX: true),
            _dragAndTargetBtn("STL", AppTheme.actionSteal,  "add_stl",   baseSize, feedSize, sf, badge: "STL"),
          ], gap),
          SizedBox(width: gap),
          _columnBtn([
            _dragAndTargetBtn("-2", AppTheme.actionMiss,    "miss_2",    baseSize, feedSize, sf, badge: ""),
            _dragAndTargetBtn("2",  AppTheme.actionPoints,  "add_pts_2", baseSize, feedSize, sf, badge: "2PM"),
            _dragAndTargetBtn("2",  AppTheme.actionPoints,  "sub_pts_2", baseSize, feedSize, sf, badge: "2PA", isX: true),
            _dragAndTargetBtn("AST", AppTheme.actionAssist, "add_ast",   baseSize, feedSize, sf, badge: "AST"),
          ], gap),
          SizedBox(width: gap),
          _columnBtn([
            _dragAndTargetBtn("-3", AppTheme.actionMiss,    "miss_3",    baseSize, feedSize, sf, badge: ""),
            _dragAndTargetBtn("3",  AppTheme.actionPoints,  "add_pts_3", baseSize, feedSize, sf, badge: "3PM"),
            _dragAndTargetBtn("3",  AppTheme.actionPoints,  "sub_pts_3", baseSize, feedSize, sf, badge: "3PA", isX: true),
            _dragAndTargetBtn("TOV", AppTheme.actionMiss,   "add_tov",   baseSize, feedSize, sf, badge: "TOV"),
          ], gap),
          SizedBox(width: gap),
          _columnBtn([
            _dragAndTargetBtn("O",   AppTheme.actionRebound, "add_orb",  baseSize, feedSize, sf, badge: "OREB"),
            _dragAndTargetBtn("D",   AppTheme.actionRebound, "add_drb",  baseSize, feedSize, sf, badge: "DREB"),
            _dragAndTargetBtn("BLK", AppTheme.actionBlock,   "add_blk",  baseSize, feedSize, sf, badge: "BLK"),
          ], gap),
        ],
      ),
    );
  }

  Widget _columnBtn(List<Widget> children, double gap) {
    return Column(
        mainAxisSize: MainAxisSize.min,
        children: children.map((c) => Padding(padding: EdgeInsets.only(bottom: gap), child: c)).toList());
  }

  Widget _dragAndTargetBtn(String label, Color color, String actionData, double baseSize, double feedSize, double sf,
      {IconData? icon, bool isX = false, String badge = ""}) {
    return Draggable<String>(
      data: actionData,
      feedback: _circle(label, color, icon, true, baseSize, feedSize, sf, isX: isX, badge: badge),
      childWhenDragging: Opacity(
        opacity: 0.5,
        child: _circle(label, color, icon, false, baseSize, feedSize, sf, isX: isX, badge: badge),
      ),
      child: DragTarget<String>(
          onAcceptWithDetails: (details) {},
          builder: (context, candidateData, rejectedData) {
            bool isHovered = candidateData.any((data) => data != null && data.startsWith("player_"));
            return Transform.scale(
              scale: isHovered ? 1.15 : 1.0,
              child: Container(
                decoration: isHovered
                    ? BoxDecoration(
                        shape: BoxShape.circle,
                        boxShadow: [BoxShadow(color: Colors.white, blurRadius: 10 * sf, spreadRadius: 3 * sf)])
                    : null,
                child: _circle(label, color, icon, false, baseSize, feedSize, sf, isX: isX, badge: badge),
              ),
            );
          }),
    );
  }

  Widget _basketball(Color color, double size) {
    return Stack(
      alignment: Alignment.center,
      children: [
        Container(
          width: size * 0.78,
          height: size * 0.78,
          decoration: const BoxDecoration(color: Colors.black, shape: BoxShape.circle),
        ),
        Icon(Icons.sports_basketball, color: color, size: size),
      ],
    );
  }

  Widget _circle(String label, Color color, IconData? icon, bool isFeed, double baseSize, double feedSize, double sf,
      {bool isX = false, String badge = ""}) {
    double size = isFeed ? feedSize : baseSize;
    Widget content;
    bool isPointBtn = label == "1" || label == "2" || label == "3" || label == "-1" || label == "-2" || label == "-3";
    bool isRebBtn   = label == "O" || label == "D";
    bool isBlkBtn   = label == "BLK";
    bool isStlBtn   = label == "STL";
    bool isAstBtn   = label == "AST";
    bool isTovBtn   = label == "TOV";

    if (isPointBtn) {
      content = Stack(
        alignment: Alignment.center,
        children: [
          _basketball(color, size * 0.9),
          Stack(
            children: [
              Text(label,
                  style: TextStyle(
                      fontSize: size * 0.38,
                      fontWeight: FontWeight.w900,
                      foreground: Paint()
                        ..style = PaintingStyle.stroke
                        ..strokeWidth = size * 0.05
                        ..color = Colors.white,
                      decoration: TextDecoration.none)),
              Text(label,
                  style: TextStyle(
                      fontSize: size * 0.38,
                      fontWeight: FontWeight.w900,
                      color: Colors.black,
                      decoration: TextDecoration.none)),
            ],
          ),
        ],
      );
    } else if (isRebBtn) {
      content = Stack(
        children: [
          Center(
            child: SizedBox(
              width: size * 0.75,
              height: size * 0.75,
              child: CustomPaint(painter: HoopIconPainter()),
            ),
          ),
          Positioned(
            top: size * -0.05,
            right: size * 0.05,
            child: Stack(
              children: [
                Text(label,
                    style: TextStyle(
                        fontSize: size * 0.48,
                        fontWeight: FontWeight.w900,
                        foreground: Paint()
                          ..style = PaintingStyle.stroke
                          ..strokeWidth = size * 0.07
                          ..color = Colors.black,
                        decoration: TextDecoration.none)),
                Text(label,
                    style: TextStyle(
                        fontSize: size * 0.48,
                        fontWeight: FontWeight.w900,
                        color: Colors.white,
                        decoration: TextDecoration.none)),
              ],
            ),
          ),
        ],
      );
    } else if (isBlkBtn) {
      content = Icon(Icons.front_hand, color: const Color.fromARGB(207, 56, 52, 52), size: size * 0.75);
    } else if (isStlBtn) {
      content = Stack(
        alignment: Alignment.center,
        children: [
          Positioned(top: size * 0.05, child: _basketball(color, size * 0.60)),
          Positioned(bottom: size * 0.10, child: Icon(Icons.pan_tool, color: color, size: size * 0.50)),
        ],
      );
    } else if (isAstBtn) {
      content = Stack(
        alignment: Alignment.center,
        children: [
          Positioned(top: size * 0.05, child: _basketball(color, size * 0.60)),
          Positioned(
            bottom: size * 0.08,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Transform(
                    alignment: Alignment.center,
                    transform: Matrix4.rotationY(3.14159),
                    child: Icon(Icons.back_hand, color: color, size: size * 0.46)),
                SizedBox(width: size * 0.04),
                Icon(Icons.back_hand, color: color, size: size * 0.46),
              ],
            ),
          ),
        ],
      );
    } else if (isTovBtn) {
      content = Stack(
        alignment: Alignment.center,
        children: [
          Positioned(top: size * 0.05, child: _basketball(color, size * 0.60)),
          Positioned(bottom: size * 0.10, child: Icon(Icons.swap_horiz_rounded, color: color, size: size * 0.55)),
        ],
      );
    } else {
      content = Text(label,
          style: TextStyle(
              color: Colors.white, fontWeight: FontWeight.bold, fontSize: size * 0.35, decoration: TextDecoration.none));
    }

    return Stack(
      clipBehavior: Clip.none,
      alignment: Alignment.bottomLeft,
      children: [
        Container(
          width: size,
          height: size,
          decoration: (isPointBtn || isBlkBtn || isRebBtn || isStlBtn || isAstBtn || isTovBtn)
              ? const BoxDecoration(color: Colors.transparent)
              : BoxDecoration(
                  gradient: RadialGradient(colors: [color.withOpacity(0.7), color], radius: 0.8),
                  shape: BoxShape.circle,
                  boxShadow: [BoxShadow(color: Colors.black38, blurRadius: 6 * sf, offset: Offset(0, 3 * sf))]),
          alignment: Alignment.center,
          child: content,
        ),
        // Badge só aparece se não for vazio
        if (badge.isNotEmpty)
          Positioned(
            bottom: size * -0.04,
            left: size * -0.04,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: size * 0.09, vertical: size * 0.02),
              decoration: BoxDecoration(
                color: Colors.grey.shade600,
                borderRadius: BorderRadius.circular(size * 0.07),
                boxShadow: [BoxShadow(color: Colors.black45, blurRadius: 2, offset: const Offset(0, 1))],
              ),
              child: Text(
                badge,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: size * 0.16,
                  fontWeight: FontWeight.w900,
                  decoration: TextDecoration.none,
                  letterSpacing: 0.2,
                ),
              ),
            ),
          ),
        if (isX)
          Positioned(
              top: 0,
              right: 0,
              child: Container(
                  decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle),
                  child: Icon(Icons.cancel, color: Colors.red, size: size * 0.4))),
      ],
    );
  }
}

class HoopIconPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final double w = size.width;
    final double h = size.height;

    final Paint paint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.stroke
      ..strokeWidth = w * 0.08
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round;

    canvas.drawRRect(
        RRect.fromRectAndRadius(Rect.fromLTRB(w * 0.02, h * 0.02, w * 0.98, h * 0.70), Radius.circular(w * 0.05)), paint);
    canvas.drawRect(Rect.fromLTRB(w * 0.28, h * 0.30, w * 0.72, h * 0.70), paint);

    final Paint rimPaint = Paint()
      ..color = Colors.orange
      ..style = PaintingStyle.stroke
      ..strokeWidth = w * 0.09
      ..strokeCap = StrokeCap.round;

    canvas.drawLine(Offset(w * 0.20, h * 0.75), Offset(w * 0.80, h * 0.75), rimPaint);

    final Paint netPaint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.stroke
      ..strokeWidth = w * 0.05;

    canvas.drawLine(Offset(w * 0.25, h * 0.75), Offset(w * 0.40, h * 0.98), netPaint);
    canvas.drawLine(Offset(w * 0.75, h * 0.75), Offset(w * 0.60, h * 0.98), netPaint);
    canvas.drawLine(Offset(w * 0.40, h * 0.75), Offset(w * 0.30, h * 0.98), netPaint);
    canvas.drawLine(Offset(w * 0.55, h * 0.75), Offset(w * 0.65, h * 0.98), netPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}