import 'package:flutter/material.dart';
import 'package:playmaker/grafico%20de%20pizza/widgets/grafico_widgets.dart'; 
import 'dados_grafico.dart';
import 'dart:math' as math;

class PieChartCard extends StatefulWidget {
  final int victories;
  final int defeats;
  final int draws;
  final String title;
  final String subtitle;
  final Color backgroundColor;
  final VoidCallback? onTap;
  final double sf;

  const PieChartCard({
    super.key,
    this.victories = 0,
    this.defeats = 0,
    this.draws = 0,
    this.title = 'DESEMPENHO',
    this.subtitle = 'Temporada',
    this.onTap, 
    required this.backgroundColor,
    this.sf = 1.0, 
  });

  @override
  State<PieChartCard> createState() => _PieChartCardState();
}

class _PieChartCardState extends State<PieChartCard> with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(duration: const Duration(milliseconds: 600), vsync: this);
    _animation = Tween<double>(begin: 0.0, end: 1.0).animate(CurvedAnimation(parent: _animationController, curve: Curves.easeOutBack));
    _animationController.forward();
  }

  @override
  void didUpdateWidget(PieChartCard oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.victories != widget.victories || oldWidget.defeats != widget.defeats || oldWidget.draws != widget.draws) {
      _animationController.reset();
      _animationController.forward();
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final data = PieChartData(victories: widget.victories, defeats: widget.defeats, draws: widget.draws);
    
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return Transform.scale(
          scale: 0.95 + (_animation.value * 0.05), 
          child: Opacity(opacity: _animation.value.clamp(0.0, 1.0), child: child),
        );
      },
      child: Card(
        margin: EdgeInsets.zero,
        elevation: 8,
        shadowColor: Colors.black54,
        clipBehavior: Clip.antiAlias,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        child: InkWell(
          onTap: widget.onTap,
          child: Container(
            decoration: BoxDecoration(
              color: const Color(0xFF1A222D), 
            ),
            child: LayoutBuilder(
              builder: (context, constraints) {
                final double ch = constraints.maxHeight; 
                final double cw = constraints.maxWidth;  
                
                return Padding(
                  padding: EdgeInsets.symmetric(horizontal: cw * 0.05, vertical: ch * 0.03), 
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // --- CABEÇALHO ---
                      FittedBox(
                        fit: BoxFit.scaleDown,
                        child: Text(widget.title.toUpperCase(), 
                          style: TextStyle(fontSize: ch * 0.045, fontWeight: FontWeight.bold, color: Colors.white70, letterSpacing: 1.2)),
                      ),
                      Text(widget.subtitle, 
                          style: TextStyle(fontSize: ch * 0.055, fontWeight: FontWeight.bold, color: Colors.white)),
                      
                      const Expanded(flex: 1, child: SizedBox()), 

                      // --- MIOLO (GRÁFICO + STATS GIGANTES À ESQUERDA) ---
                      Expanded(
                        flex: 9, 
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start, 
                          children: [
                            // 1. Lado Esquerdo: Donut Chart LIMPO (Sem texto sobreposto)
                            SizedBox(
                              width: cw * 0.38, 
                              height: cw * 0.38, 
                              child: PieChartWidget(
                                victoryPercentage: data.victoryPercentage,
                                defeatPercentage: data.defeatPercentage,
                                drawPercentage: data.drawPercentage,
                                sf: widget.sf,
                              ),
                            ),

                            SizedBox(width: cw * 0.08), 

                            // 2. Lado Direito: Números Dinâmicos
                            Expanded(
                              child: FittedBox( 
                                alignment: Alignment.centerLeft, 
                                fit: BoxFit.scaleDown,
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  crossAxisAlignment: CrossAxisAlignment.start, 
                                  children: [
                                    _buildDynStatRow("VIT", data.victories.toString(), (data.victoryPercentage * 100).toStringAsFixed(0), Colors.greenAccent, ch, cw),
                                    _buildDynStatRow("EMP", data.draws.toString(), (data.drawPercentage * 100).toStringAsFixed(0), Colors.yellowAccent, ch, cw),
                                    _buildDynStatRow("DER", data.defeats.toString(), (data.defeatPercentage * 100).toStringAsFixed(0), Colors.redAccent, ch, cw),
                                    _buildDynDivider(cw),
                                    _buildDynStatRow("TOT", data.total.toString(), "100", Colors.white, ch, cw),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      
                      const Expanded(flex: 1, child: SizedBox()), 

                      // --- RODAPÉ: BOTÃO WIN RATE GIGANTE ---
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.symmetric(vertical: ch * 0.025), 
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.08), 
                          borderRadius: BorderRadius.circular(12), 
                        ),
                        child: FittedBox( 
                          fit: BoxFit.scaleDown,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(Icons.stars, color: Colors.greenAccent, size: ch * 0.075), 
                              const SizedBox(width: 10),
                              Text('WIN RATE: ${(data.victoryPercentage * 100).toStringAsFixed(1)}%', 
                                style: TextStyle(
                                  color: Colors.white, 
                                  fontWeight: FontWeight.w900, 
                                  letterSpacing: 1.0,
                                  fontSize: ch * 0.06 
                                ),
                              ), 
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              }
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDynStatRow(String label, String number, String percent, Color color, double ch, double cw) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: ch * 0.005), 
      child: Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: cw * 0.12, 
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end, 
              mainAxisSize: MainAxisSize.min, 
              children: [
                Text(label, style: TextStyle(fontSize: ch * 0.035, color: Colors.white60, fontWeight: FontWeight.bold)), 
                Text('$percent%', style: TextStyle(fontSize: ch * 0.04, color: color, fontWeight: FontWeight.bold)), 
              ],
            ),
          ),
          SizedBox(width: cw * 0.03), 
          Text(number, style: TextStyle(fontSize: ch * 0.125, fontWeight: FontWeight.w900, color: color, height: 1)),
        ],
      ),
    );
  }

  Widget _buildDynDivider(double cw) {
    return Container(
      width: cw * 0.35, 
      height: 1.5, 
      color: Colors.white24, 
      margin: const EdgeInsets.symmetric(vertical: 4) 
    );
  }
}