import 'package:flutter/material.dart';
import 'package:playmaker/grafico%20de%20pizza/widgets/grafico_widgets.dart'; 
import 'dados_grafico.dart';
import 'package:playmaker/classe/theme.dart'; // 👇 IMPORT DO TEMA ADICIONADO PARA USARMOS O primaryRed
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, 
    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);
    
    // 👇 BLINDAGEM DO FUNDO E DO TEXTO PARA MODO CLARO/ESCURO
    final Color cardColor = widget.backgroundColor ?? Theme.of(context).cardTheme.color ?? (Theme.of(context).brightness == Brightness.dark ? const Color(0xFF1E1E1E) : Colors.white);
    final Color textColor = Theme.of(context).colorScheme.onSurface;

    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: 0, // Ajustado para não ter sombra dupla, já que o tema pode ter
        clipBehavior: Clip.antiAlias,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
          side: BorderSide(color: Colors.grey.withOpacity(0.15)), // Borda suave igual ao resto da app
        ),
        child: InkWell(
          onTap: widget.onTap,
          child: Container(
            decoration: BoxDecoration(
              color: cardColor, // 👇 APLICA A COR BLINDADA
            ),
            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 --- (👇 MANTIDO ALINHADO À ESQUERDA)
                      FittedBox(
                        fit: BoxFit.scaleDown,
                        child: Text(widget.title.toUpperCase(), 
                          style: TextStyle(
                            fontSize: ch * 0.045, 
                            fontWeight: FontWeight.bold, 
                            color: AppTheme.primaryRed, // 👇 USANDO O TEU primaryRed
                            letterSpacing: 1.2
                          )
                        ), 
                      ),
                      Text(widget.subtitle, 
                          style: TextStyle(
                            fontSize: ch * 0.055, 
                            fontWeight: FontWeight.bold, 
                            color: AppTheme.backgroundLight, // 👇 USANDO O TEU backgroundLight
                          )
                      ),
                      
                      const Expanded(flex: 1, child: SizedBox()), 

                      // --- MIOLO (GRÁFICO MAIOR À ESQUERDA + STATS) ---
                                           Expanded(
                        flex: 9, 
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end, // Changed from spaceBetween to end to push stats more to the right
                          children: [
                            // 1. Lado Esquerdo: Donut Chart
                            // 👇 MUDANÇA AQUI: Gráfico ainda maior! cw * 0.52
                            SizedBox(
                              width: cw * 0.52, 
                              height: cw * 0.52, 
                              child: PieChartWidget(
                                victoryPercentage: data.victoryPercentage,
                                defeatPercentage: data.defeatPercentage,
                                drawPercentage: data.drawPercentage,
                                sf: widget.sf,
                              ),
                            ),

                            SizedBox(width: cw * 0.005), // Reduzi o espaço no meio para dar lugar ao gráfico

                            // 2. Lado Direito: Números Dinâmicos
                            Expanded(
                              child: FittedBox( 
                                alignment: Alignment.centerRight, // Encosta os números à direita
                                fit: BoxFit.scaleDown,
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  crossAxisAlignment: CrossAxisAlignment.end, // Alinha os números à direita para ficar arrumado
                                  children: [
                                    _buildDynStatRow("VIT", data.victories.toString(), (data.victoryPercentage * 100).toStringAsFixed(0), Colors.green, textColor, ch, cw),
                                    _buildDynStatRow("EMP", data.draws.toString(), (data.drawPercentage * 100).toStringAsFixed(0), Colors.amber, textColor, ch, cw),
                                    _buildDynStatRow("DER", data.defeats.toString(), (data.defeatPercentage * 100).toStringAsFixed(0), Colors.red, textColor, ch, cw),
                                    _buildDynDivider(cw, textColor),
                                    _buildDynStatRow("TOT", data.total.toString(), "100", textColor, textColor, ch, cw),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      const Expanded(flex: 1, child: SizedBox()), 

                      // --- RODAPÉ: BOTÃO WIN RATE GIGANTE --- (👇 MUDANÇA AQUI: Alinhado à esquerda)
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.symmetric(vertical: ch * 0.025), 
                        decoration: BoxDecoration(
                          color: textColor.withOpacity(0.05), // 👇 Fundo adaptável
                          borderRadius: BorderRadius.circular(12), 
                        ),
                        child: FittedBox( 
                          fit: BoxFit.scaleDown,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start, // 👇 MUDANÇA AQUI: Letras mais para a esquerda!
                            children: [
                              Icon(Icons.stars, color: Colors.green, size: ch * 0.075), 
                              const SizedBox(width: 10),
                              Text('WIN RATE: ${(data.victoryPercentage * 100).toStringAsFixed(1)}%', 
                                style: TextStyle(
                                 color: AppTheme.backgroundLight,
                                  fontWeight: FontWeight.w900, 
                                  letterSpacing: 1.0,
                                  fontSize: ch * 0.06 
                                ),
                              ), 
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              }
            ),
          ),
        ),
      ),
    );
  }

  // 👇 Ajustei a linha de stats para alinhar melhor agora que os números estão encostados à direita
  Widget _buildDynStatRow(String label, String number, String percent, Color statColor, Color textColor, 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.045, color: textColor.withOpacity(0.6), fontWeight: FontWeight.bold)), // 👇 TEXTO ADAPTÁVEL (increased from 0.035)
                Text('$percent%', style: TextStyle(fontSize: ch * 0.05, color: statColor, fontWeight: FontWeight.bold)), // (increased from 0.04)
              ],
            ),
          ),
          SizedBox(width: cw * 0.03), 
          Text(number, style: TextStyle(fontSize: ch * 0.15, fontWeight: FontWeight.w900, color: statColor, height: 1)), // (increased from 0.125)
        ],
      ),
    );
  }

  Widget _buildDynDivider(double cw, Color textColor) {
    return Container(
      width: cw * 0.35, 
      height: 1.5, 
      color: textColor.withOpacity(0.2), // 👇 LINHA ADAPTÁVEL
      margin: const EdgeInsets.symmetric(vertical: 4) 
    );
  }
}