import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'dart:math' show cos, sin;

import '../../../../../../common/theme/theme.dart';

@RoutePage()
class DrawWinnerPage extends StatefulWidget {
  const DrawWinnerPage({super.key});

  @override
  State<DrawWinnerPage> createState() => _DrawWinnerPageState();
}

class _DrawWinnerPageState extends State<DrawWinnerPage>
    with TickerProviderStateMixin {
  late AnimationController _fadeController;
  late AnimationController _slideController;
  late AnimationController _scaleController;
  late AnimationController _pulseController;
  late AnimationController _celebrationController;

  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;
  late Animation<double> _scaleAnimation;
  late Animation<double> _pulseAnimation;
  late Animation<double> _celebrationAnimation;

  @override
  void initState() {
    super.initState();

    _fadeController = AnimationController(
      duration: Duration(milliseconds: 1200),
      vsync: this,
    );

    _slideController = AnimationController(
      duration: Duration(milliseconds: 800),
      vsync: this,
    );

    _scaleController = AnimationController(
      duration: Duration(milliseconds: 1000),
      vsync: this,
    );

    _pulseController = AnimationController(
      duration: Duration(milliseconds: 2000),
      vsync: this,
    );

    _celebrationController = AnimationController(
      duration: Duration(milliseconds: 3000),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _fadeController, curve: Curves.easeInOut),
    );

    _slideAnimation = Tween<Offset>(begin: Offset(0, 0.3), end: Offset.zero)
        .animate(
          CurvedAnimation(parent: _slideController, curve: Curves.easeOutCubic),
        );

    _scaleAnimation = Tween<double>(begin: 0.8, end: 1.0).animate(
      CurvedAnimation(parent: _scaleController, curve: Curves.elasticOut),
    );

    _pulseAnimation = Tween<double>(begin: 1.0, end: 1.05).animate(
      CurvedAnimation(parent: _pulseController, curve: Curves.easeInOut),
    );

    _celebrationAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _celebrationController, curve: Curves.elasticOut),
    );

    _startAnimations();
  }

  void _startAnimations() async {
    await Future.delayed(Duration(milliseconds: 100));
    _fadeController.forward();

    await Future.delayed(Duration(milliseconds: 200));
    _slideController.forward();

    await Future.delayed(Duration(milliseconds: 300));
    _scaleController.forward();

    await Future.delayed(Duration(milliseconds: 600));
    _celebrationController.forward();

    await Future.delayed(Duration(milliseconds: 800));
    _pulseController.repeat(reverse: true);
  }

  @override
  void dispose() {
    _fadeController.dispose();
    _slideController.dispose();
    _scaleController.dispose();
    _pulseController.dispose();
    _celebrationController.dispose();
    super.dispose();
  }

  Widget _buildTitle() {
    return SlideTransition(
      position: _slideAnimation,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        child: Row(
          children: [
            Container(
              width: 3,
              height: 28,
              decoration: BoxDecoration(
                color: AppColor.white,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            SizedBox(width: 12),
            Text(
              'Pemenang',
              style: AppStyle.h3.copyWith(
                color: AppColor.textWhite,
                fontWeight: FontWeight.w600,
                letterSpacing: -0.5,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTodayWinnerBanner() {
    return ScaleTransition(
      scale: _scaleAnimation,
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 20),
        decoration: BoxDecoration(
          color: AppColor.white,
          borderRadius: BorderRadius.circular(24),
          boxShadow: [
            BoxShadow(
              color: AppColor.warning.withOpacity(0.3),
              blurRadius: 30,
              spreadRadius: 0,
              offset: Offset(0, 15),
            ),
          ],
        ),
        child: Stack(
          children: [
            // Celebration Particles Effect
            Positioned.fill(
              child: AnimatedBuilder(
                animation: _celebrationAnimation,
                builder: (context, child) {
                  return CustomPaint(
                    painter: CelebrationPainter(_celebrationAnimation.value),
                  );
                },
              ),
            ),

            // Main Content
            Padding(
              padding: EdgeInsets.all(24),
              child: Column(
                children: [
                  // Trophy Icon with Animation
                  AnimatedBuilder(
                    animation: _celebrationAnimation,
                    builder: (context, child) {
                      return Transform.scale(
                        scale: _celebrationAnimation.value,
                        child: Transform.rotate(
                          angle: _celebrationAnimation.value * 0.1,
                          child: Container(
                            padding: EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                colors: [
                                  AppColor.warning,
                                  AppColor.warning.withOpacity(0.8),
                                ],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              ),
                              shape: BoxShape.circle,
                              boxShadow: [
                                BoxShadow(
                                  color: AppColor.warning.withOpacity(0.4),
                                  blurRadius: 20,
                                  offset: Offset(0, 8),
                                ),
                              ],
                            ),
                            child: Icon(
                              Icons.emoji_events_rounded,
                              color: AppColor.white,
                              size: 32,
                            ),
                          ),
                        ),
                      );
                    },
                  ),

                  SizedBox(height: 16),

                  // Title with Emoji
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        'Pemenang Hari Ini',
                        style: AppStyle.lg.copyWith(
                          color: AppColor.primary,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                      SizedBox(width: 8),
                      TweenAnimationBuilder<double>(
                        tween: Tween(begin: 0.0, end: 1.0),
                        duration: Duration(milliseconds: 1500),
                        curve: Curves.elasticOut,
                        builder: (context, value, child) {
                          return Transform.scale(
                            scale: value,
                            child: Text('🎉', style: TextStyle(fontSize: 20)),
                          );
                        },
                      ),
                    ],
                  ),

                  SizedBox(height: 20),

                  // Winning Number
                  AnimatedBuilder(
                    animation: _pulseAnimation,
                    builder: (context, child) {
                      return Transform.scale(
                        scale: _pulseAnimation.value,
                        child: Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 20,
                            vertical: 16,
                          ),
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [
                                AppColor.primary.withOpacity(0.05),
                                AppColor.primary.withOpacity(0.02),
                              ],
                              begin: Alignment.topLeft,
                              end: Alignment.bottomRight,
                            ),
                            borderRadius: BorderRadius.circular(16),
                            border: Border.all(
                              color: AppColor.primary.withOpacity(0.1),
                              width: 1,
                            ),
                          ),
                          child: Text(
                            '849302',
                            style: TextStyle(
                              color: AppColor.primary,
                              fontSize: 36,
                              fontWeight: FontWeight.w900,
                              letterSpacing: 8,
                              height: 1.0,
                            ),
                          ),
                        ),
                      );
                    },
                  ),

                  SizedBox(height: 16),

                  // Winner Name
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: AppColor.primaryGradient,
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ),
                      borderRadius: BorderRadius.circular(20),
                      boxShadow: [
                        BoxShadow(
                          color: AppColor.primary.withOpacity(0.3),
                          blurRadius: 12,
                          offset: Offset(0, 4),
                        ),
                      ],
                    ),
                    child: Text(
                      'Selamat untuk Andi***',
                      style: AppStyle.md.copyWith(
                        color: AppColor.white,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHistorySection() {
    return SlideTransition(
      position: Tween<Offset>(begin: Offset(0, 0.5), end: Offset.zero).animate(
        CurvedAnimation(
          parent: _slideController,
          curve: Interval(0.3, 1.0, curve: Curves.easeOutCubic),
        ),
      ),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Pemenang Kemarin',
              style: AppStyle.lg.copyWith(
                color: AppColor.textWhite,
                fontWeight: FontWeight.w600,
              ),
            ),
            SizedBox(height: 12),
          ],
        ),
      ),
    );
  }

  Widget _buildWinnerCard(String number, String name, String date, int index) {
    return TweenAnimationBuilder<double>(
      tween: Tween(begin: 0.0, end: 1.0),
      duration: Duration(milliseconds: 800 + (index * 200)),
      curve: Curves.easeOutCubic,
      builder: (context, value, child) {
        return Transform.translate(
          offset: Offset(0, 30 * (1 - value)),
          child: Opacity(
            opacity: value,
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 20, vertical: 6),
              padding: EdgeInsets.all(18),
              decoration: BoxDecoration(
                color: AppColor.white.withOpacity(0.12),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                  color: AppColor.white.withOpacity(0.2),
                  width: 1,
                ),
                boxShadow: [
                  BoxShadow(
                    color: AppColor.black.withOpacity(0.05),
                    blurRadius: 15,
                    offset: Offset(0, 8),
                  ),
                ],
              ),
              child: Row(
                children: [
                  // Trophy Icon
                  Container(
                    padding: EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          AppColor.warning,
                          AppColor.warning.withOpacity(0.8),
                        ],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ),
                      borderRadius: BorderRadius.circular(16),
                      boxShadow: [
                        BoxShadow(
                          color: AppColor.warning.withOpacity(0.3),
                          blurRadius: 12,
                          offset: Offset(0, 4),
                        ),
                      ],
                    ),
                    child: Icon(
                      Icons.emoji_events_rounded,
                      color: AppColor.white,
                      size: 20,
                    ),
                  ),

                  SizedBox(width: 16),

                  // Winner Info
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          number,
                          style: AppStyle.md.copyWith(
                            color: AppColor.white,
                            fontWeight: FontWeight.w700,
                            letterSpacing: 2,
                          ),
                        ),
                        SizedBox(height: 4),
                        Text(
                          name,
                          style: AppStyle.sm.copyWith(
                            color: AppColor.warning,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        SizedBox(height: 2),
                        Text(
                          date,
                          style: AppStyle.xs.copyWith(
                            color: AppColor.white.withOpacity(0.7),
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),

                  // Winner Badge
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: AppColor.success.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(
                        color: AppColor.success.withOpacity(0.3),
                        width: 1,
                      ),
                    ),
                    child: Text('🏆', style: TextStyle(fontSize: 12)),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: AppColor.primaryGradient,
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
        ),
        child: SafeArea(
          child: FadeTransition(
            opacity: _fadeAnimation,
            child: ListView(
              physics: BouncingScrollPhysics(),
              children: [
                SizedBox(height: 20),

                // Title
                _buildTitle(),

                SizedBox(height: 24),

                // Today's Winner Banner
                _buildTodayWinnerBanner(),

                SizedBox(height: 24),

                // History Section Title
                _buildHistorySection(),

                // Winner History Cards
                _buildWinnerCard('138472', 'Budi***', 'Kemarin', 0),
                _buildWinnerCard('928374', 'Sari***', '2 hari lalu', 1),
                _buildWinnerCard('475829', 'Dono***', '3 hari lalu', 2),
                _buildWinnerCard('629384', 'Lisa***', '4 hari lalu', 3),

                SizedBox(height: 20),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// Custom painter for celebration particles effect
class CelebrationPainter extends CustomPainter {
  final double animationValue;

  CelebrationPainter(this.animationValue);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..style = PaintingStyle.fill;

    // Draw floating particles
    for (int i = 0; i < 8; i++) {
      final angle = (i * 45) * (3.14159 / 180);
      final radius = animationValue * 40;
      final x = size.width / 2 + radius * cos(angle);
      final y = size.height / 2 + radius * sin(angle);

      paint.color = AppColor.warning.withOpacity(0.3 * animationValue);
      canvas.drawCircle(Offset(x, y), 2 * animationValue, paint);
    }
  }

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