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

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(
          // O scale pode passar de 1.0 (efeito back), mas a opacidade NÃO
          scale: 0.95 + (_animation.value * 0.05), 
          child: Opacity(
            // 👇 AQUI ESTÁ A FIX: Garante que fica entre 0 e 1
            opacity: _animation.value.clamp(0.0, 1.0), 
            child: child,
          ),
        );
      },
      child: Card(
        margin: EdgeInsets.zero,
        elevation: 4, 
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
        child: InkWell(
          onTap: widget.onTap,
          borderRadius: BorderRadius.circular(14),
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(14),
              gradient: LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [widget.backgroundColor.withOpacity(0.9), widget.backgroundColor.withOpacity(0.7)]),
            ),
            child: LayoutBuilder(
              builder: (context, constraints) {
                final double ch = constraints.maxHeight; 
                final double cw = constraints.maxWidth;  
                
                return Padding(
                  padding: EdgeInsets.all(cw * 0.06), 
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 👇 TÍTULOS UM POUCO MAIS PRESENTES
                      FittedBox(
                        fit: BoxFit.scaleDown,
                        child: Text(widget.title.toUpperCase(), style: TextStyle(fontSize: ch * 0.06, fontWeight: FontWeight.bold, color: Colors.white.withOpacity(0.9), letterSpacing: 1.0)),
                      ),
                      FittedBox(
                        fit: BoxFit.scaleDown,
                        child: Text(widget.subtitle, style: TextStyle(fontSize: ch * 0.07, fontWeight: FontWeight.bold, color: Colors.white)),
                      ),
                      
                      SizedBox(height: ch * 0.03),

                      // MEIO (GRÁFICO + ESTATÍSTICAS)
                      Expanded(
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Expanded(
                              flex: 1,
                              child: PieChartWidget(
                                victoryPercentage: data.victoryPercentage,
                                defeatPercentage: data.defeatPercentage,
                                drawPercentage: data.drawPercentage,
                                sf: widget.sf, 
                              ),
                            ),
                            SizedBox(width: cw * 0.05),
                            Expanded(
                              flex: 1,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  _buildDynStatRow("VIT", data.victories.toString(), (data.victoryPercentage * 100).toStringAsFixed(0), Colors.green, ch),
                                  _buildDynStatRow("EMP", data.draws.toString(), (data.drawPercentage * 100).toStringAsFixed(0), Colors.yellow, ch),
                                  _buildDynStatRow("DER", data.defeats.toString(), (data.defeatPercentage * 100).toStringAsFixed(0), Colors.red, ch),
                                  _buildDynDivider(ch),
                                  _buildDynStatRow("TOT", data.total.toString(), "100", Colors.white, ch),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      
                      // 👇 RODAPÉ AJUSTADO
                     SizedBox(height: ch * 0.03),
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.symmetric(vertical: ch * 0.035),
                        decoration: BoxDecoration(
                          color: Colors.white24, // Igual ao fundo do botão detalhes
                          borderRadius: BorderRadius.circular(ch * 0.03), // Borda arredondada
                        ),
                        child: Center(
                          child: FittedBox(
                            fit: BoxFit.scaleDown,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  data.victoryPercentage >= 0.5 ? Icons.trending_up : Icons.trending_down, 
                                  color: Colors.green, 
                                  size: ch * 0.09
                                ),
                                SizedBox(width: cw * 0.02),
                                Text(
                                  'WIN RATE: ${(data.victoryPercentage * 100).toStringAsFixed(1)}%', 
                                  style: TextStyle(
                                    fontSize: ch * 0.05, 
                                    fontWeight: FontWeight.bold, 
                                    color: Colors.white
                                  )
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              }
            ),
          ),
        ),
      ),
    );
  }
  // 👇 PERCENTAGENS SUBIDAS LIGEIRAMENTE (0.10 e 0.045)
  Widget _buildDynStatRow(String label, String number, String percent, Color color, double ch) {
    return Padding(
      padding: EdgeInsets.only(bottom: ch * 0.01), 
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // Número subiu para 0.10
          Expanded(flex: 2, child: FittedBox(fit: BoxFit.scaleDown, alignment: Alignment.centerLeft, child: Text(number, style: TextStyle(fontSize: ch * 0.10, fontWeight: FontWeight.bold, color: color, height: 1.0)))),
          SizedBox(width: ch * 0.02),
          Expanded(
            flex: 3,
            child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [
              Row(children: [
                Container(width: ch * 0.018, height: ch * 0.018, margin: EdgeInsets.only(right: ch * 0.015), decoration: BoxDecoration(color: color, shape: BoxShape.circle)), 
                // Label subiu para 0.045
                Expanded(child: FittedBox(fit: BoxFit.scaleDown, alignment: Alignment.centerLeft, child: Text(label, style: TextStyle(fontSize: ch * 0.033, color: Colors.white.withOpacity(0.8), fontWeight: FontWeight.w600))))
              ]),
              // Percentagem subiu para 0.05
              FittedBox(fit: BoxFit.scaleDown, alignment: Alignment.centerLeft, child: Text('$percent%', style: TextStyle(fontSize: ch * 0.04, color: color, fontWeight: FontWeight.bold))),
            ]),
          ),
        ],
      ),
    );
  }

  Widget _buildDynDivider(double ch) {
    return Container(height: 0.5, color: Colors.white.withOpacity(0.1), margin: EdgeInsets.symmetric(vertical: ch * 0.01));
  }
}