import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'dart:math' as math;

import '../../../../application/auth/auth_bloc.dart';
import '../../../../application/game/game_price_loader/game_prize_loader_bloc.dart';
import '../../../../common/theme/theme.dart';
import '../../../../common/painter/wheel_painter.dart';
import '../../../../injection.dart';
import '../../../../domain/game/game.dart';
import 'data/model.dart';

@RoutePage()
class FerrisWheelPage extends StatefulWidget implements AutoRouteWrapper {
  const FerrisWheelPage({super.key});

  @override
  State<FerrisWheelPage> createState() => _FerrisWheelPageState();

  @override
  Widget wrappedRoute(BuildContext context) => BlocProvider(
    create: (context) => getIt<GamePrizeLoaderBloc>()
      ..add(
        const GamePrizeLoaderEvent.fetched(
          '28d5aed3-4c1b-4b7b-bad5-67cdd4919dc2',
        ),
      ),
    child: this,
  );
}

class _FerrisWheelPageState extends State<FerrisWheelPage>
    with TickerProviderStateMixin {
  // Animation Controllers
  late AnimationController _rotationController;
  late AnimationController _glowController;
  late AnimationController _pulseController;
  late AnimationController _idleRotationController;

  // Animations
  Animation<double>? _spinAnimation;
  Animation<double>? _pulseAnimation;
  Animation<double>? _idleRotationAnimation;

  // Audio Players
  final AudioPlayer _bgmPlayer = AudioPlayer();
  final AudioPlayer _sfxPlayer = AudioPlayer();

  // Audio Settings
  bool _isSoundEnabled = true;
  bool _isMusicEnabled = true;

  // Game State
  int tokens = 3;
  bool isSpinning = false;
  String resultText = 'Belum pernah spin';
  double currentRotation = 0.0;
  int currentTabIndex = 0;

  // Game Data
  List<PrizeHistory> prizeHistory = [];
  List<GamePrize> gamePrizes = [];

  @override
  void initState() {
    super.initState();
    _initializeAudio();
    _initializeAnimations();
  }

  @override
  void dispose() {
    _rotationController.dispose();
    _glowController.dispose();
    _pulseController.dispose();
    _idleRotationController.dispose();
    _bgmPlayer.dispose();
    _sfxPlayer.dispose();
    super.dispose();
  }

  void _initializeAudio() async {
    try {
      await _bgmPlayer.setSource(
        AssetSource('audio/carnival/bgm/carnival_main_theme.mp3'),
      );
      await _bgmPlayer.setReleaseMode(ReleaseMode.loop);
      await _bgmPlayer.setVolume(0.5);
      if (_isMusicEnabled) _bgmPlayer.resume();
    } catch (e) {
      print('Error initializing audio: $e');
    }
  }

  void _playSound(String soundPath, {double volume = 0.7}) async {
    if (!_isSoundEnabled) return;
    try {
      await _sfxPlayer.stop();
      await _sfxPlayer.setSource(AssetSource(soundPath));
      await _sfxPlayer.setVolume(volume);
      await _sfxPlayer.resume();
    } catch (e) {
      print('Error playing sound: $e');
    }
  }

  void _playButtonTap() =>
      _playSound('audio/carnival/sfx/button_tap.mp3', volume: 0.3);
  void _playTokenSound() =>
      _playSound('audio/carnival/sfx/token_sound.mp3', volume: 0.5);
  void _playWheelSpin() =>
      _playSound('audio/carnival/sfx/wheel_spin.mp3', volume: 0.8);

  void _playWinSound(GamePrize prize) {
    int prizeValue = prize.metadata['value'] ?? prize.weight;
    if (prizeValue >= 1000000) {
      _playSound('audio/carnival/sfx/win_big.mp3', volume: 0.9);
    } else if (prizeValue >= 5000) {
      _playSound('audio/carnival/sfx/win_medium.mp3', volume: 0.8);
    } else {
      _playSound('audio/carnival/sfx/win_small.mp3', volume: 0.7);
    }
  }

  void _toggleSound() {
    setState(() => _isSoundEnabled = !_isSoundEnabled);
    if (_isSoundEnabled) _playButtonTap();
  }

  void _toggleMusic() {
    setState(() => _isMusicEnabled = !_isMusicEnabled);
    _isMusicEnabled ? _bgmPlayer.resume() : _bgmPlayer.pause();
    if (_isSoundEnabled) _playButtonTap();
  }

  void _initializeAnimations() {
    _rotationController = AnimationController(
      duration: const Duration(seconds: 4),
      vsync: this,
    );
    _glowController = AnimationController(
      duration: const Duration(milliseconds: 2000),
      vsync: this,
    );
    _pulseController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    _idleRotationController = AnimationController(
      duration: const Duration(seconds: 10),
      vsync: this,
    );

    _pulseAnimation = Tween<double>(begin: 1.0, end: 1.1).animate(
      CurvedAnimation(parent: _pulseController, curve: Curves.easeInOut),
    );
    _idleRotationAnimation = Tween<double>(
      begin: 0.0,
      end: 2 * math.pi,
    ).animate(_idleRotationController);

    _glowController.repeat(reverse: true);
    _pulseController.repeat(reverse: true);
    _idleRotationController.repeat();
  }

  int _selectPrizeWithWeight() {
    if (gamePrizes.isEmpty) return 0;

    final availablePrizes = gamePrizes
        .asMap()
        .entries
        .where((entry) => entry.value.stock > 0)
        .toList();

    if (availablePrizes.isEmpty) {
      return math.Random().nextInt(gamePrizes.length);
    }

    int totalWeight = availablePrizes
        .map((entry) => entry.value.weight)
        .reduce((a, b) => a + b);

    if (totalWeight <= 0) {
      final randomEntry =
          availablePrizes[math.Random().nextInt(availablePrizes.length)];
      return randomEntry.key;
    }

    int randomWeight = math.Random().nextInt(totalWeight);
    int currentWeight = 0;

    for (final entry in availablePrizes) {
      currentWeight += entry.value.weight;
      if (randomWeight < currentWeight) {
        return entry.key;
      }
    }

    return availablePrizes.last.key;
  }

  Color _getPrizeColor(GamePrize prize, int index) {
    final colorName = prize.metadata['color'] as String?;
    switch (colorName?.toLowerCase()) {
      case 'primary':
        return AppColor.primary;
      case 'info':
        return AppColor.info;
      case 'warning':
        return AppColor.warning;
      case 'success':
        return AppColor.success;
      case 'error':
        return AppColor.error;
      case 'secondary':
        return AppColor.secondary;
      default:
        final colors = [
          AppColor.primary,
          AppColor.info,
          AppColor.warning,
          AppColor.success,
          AppColor.primaryDark,
          AppColor.secondary,
          AppColor.error,
        ];
        return colors[index % colors.length];
    }
  }

  void _spinWheel() {
    if (isSpinning || tokens <= 0 || gamePrizes.isEmpty) return;

    _playWheelSpin();
    _playTokenSound();

    setState(() {
      isSpinning = true;
      tokens--;
      resultText = 'Sedang berputar...';
    });

    _idleRotationController.stop();

    int targetSection = _selectPrizeWithWeight();
    double sectionAngle = (2 * math.pi) / gamePrizes.length;
    double targetAngle = (targetSection * sectionAngle) + (sectionAngle / 2);
    double baseRotations = 4 + math.Random().nextDouble() * 3;
    double currentIdleRotation = _idleRotationAnimation?.value ?? 0.0;
    double finalRotation =
        currentRotation +
        currentIdleRotation +
        (baseRotations * 2 * math.pi) +
        targetAngle;

    _spinAnimation =
        Tween<double>(
          begin: currentRotation + currentIdleRotation,
          end: finalRotation,
        ).animate(
          CurvedAnimation(
            parent: _rotationController,
            curve: Curves.easeOutCubic,
          ),
        );

    _rotationController.reset();
    _rotationController.animateTo(1.0).then((_) {
      final wonPrize = gamePrizes[targetSection];
      _playWinSound(wonPrize);

      setState(() {
        currentRotation = finalRotation;
        isSpinning = false;
        resultText = 'Selamat! Anda mendapat ${wonPrize.name}!';

        if (wonPrize.stock > 0) {
          gamePrizes[targetSection] = wonPrize.copyWith(
            stock: wonPrize.stock - 1,
          );
        }

        prizeHistory.insert(
          0,
          PrizeHistory(
            prize: wonPrize.name,
            dateTime: DateTime.now(),
            value: wonPrize.metadata['value'] ?? wonPrize.weight,
            color: _getPrizeColor(wonPrize, targetSection),
            icon: Icons.card_giftcard,
            gamePrizeId: wonPrize.id,
          ),
        );
      });

      _showWinDialog(wonPrize);
      _idleRotationController.reset();
      _idleRotationController.repeat();
    });
  }

  void _showWinDialog(GamePrize wonPrize) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => Dialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        child: Container(
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: AppColor.primaryGradient,
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 80,
                height: 80,
                decoration: BoxDecoration(
                  color: AppColor.white,
                  borderRadius: BorderRadius.circular(40),
                  boxShadow: [
                    BoxShadow(
                      color: AppColor.black.withOpacity(0.2),
                      blurRadius: 15,
                      spreadRadius: 2,
                    ),
                  ],
                ),
                child: Icon(
                  Icons.card_giftcard,
                  color: AppColor.primary,
                  size: 40,
                ),
              ),
              const SizedBox(height: 16),
              Text(
                'Selamat!',
                style: AppStyle.h5.copyWith(
                  fontWeight: FontWeight.bold,
                  color: AppColor.textWhite,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                'Anda mendapatkan',
                style: AppStyle.lg.copyWith(color: AppColor.textWhite),
              ),
              const SizedBox(height: 4),
              Text(
                wonPrize.name,
                style: AppStyle.h5.copyWith(
                  fontWeight: FontWeight.bold,
                  color: AppColor.textWhite,
                ),
              ),
              if (wonPrize.stock >= 0) ...[
                const SizedBox(height: 8),
                Text(
                  'Stok tersisa: ${wonPrize.stock}',
                  style: AppStyle.sm.copyWith(
                    color: AppColor.textWhite.withOpacity(0.8),
                  ),
                ),
              ],
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  _playButtonTap();
                  Navigator.of(context).pop();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColor.white,
                  foregroundColor: AppColor.primary,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25),
                  ),
                  padding: const EdgeInsets.symmetric(
                    horizontal: 30,
                    vertical: 12,
                  ),
                ),
                child: Text(
                  'Terima Kasih',
                  style: AppStyle.md.copyWith(
                    fontWeight: FontWeight.bold,
                    color: AppColor.primary,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<GamePrizeLoaderBloc, GamePrizeLoaderState>(
      builder: (context, state) {
        if (state.isFetching) {
          return Scaffold(
            body: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: AppColor.primaryGradient,
                ),
              ),
              child: Center(
                child: SpinKitFadingCircle(color: AppColor.textWhite, size: 36),
              ),
            ),
          );
        }

        if (gamePrizes.isEmpty && state.gamePrize.isNotEmpty) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            setState(() {
              gamePrizes = state.gamePrize;
            });
          });
        }

        return Scaffold(
          body: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: AppColor.primaryGradient,
              ),
            ),
            child: SafeArea(
              child: Column(
                children: [
                  // Header
                  Container(
                    padding: const EdgeInsets.all(16),
                    child: Row(
                      children: [
                        IconButton(
                          onPressed: () {
                            _playButtonTap();
                            context.router.back();
                          },
                          icon: Icon(
                            Icons.close,
                            color: AppColor.textWhite,
                            size: 28,
                          ),
                        ),
                        Expanded(
                          child: Text(
                            'SPIN & WIN',
                            style: AppStyle.h6.copyWith(
                              fontWeight: FontWeight.bold,
                              color: AppColor.textWhite,
                              letterSpacing: 2,
                            ),
                          ),
                        ),
                        IconButton(
                          onPressed: _toggleMusic,
                          icon: Icon(
                            _isMusicEnabled
                                ? Icons.volume_up
                                : Icons.volume_off,
                            color: AppColor.textWhite,
                          ),
                        ),
                        IconButton(
                          onPressed: _toggleSound,
                          icon: Icon(
                            _isSoundEnabled
                                ? Icons.graphic_eq
                                : Icons.volume_mute,
                            color: AppColor.textWhite,
                          ),
                        ),
                      ],
                    ),
                  ),

                  // Tab Selector
                  Container(
                    margin: const EdgeInsets.symmetric(horizontal: 20),
                    decoration: BoxDecoration(
                      color: AppColor.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(25),
                    ),
                    child: Row(
                      children: [
                        for (int i = 0; i < 3; i++)
                          Expanded(
                            child: GestureDetector(
                              onTap: () {
                                _playButtonTap();
                                setState(() => currentTabIndex = i);
                              },
                              child: Container(
                                padding: const EdgeInsets.symmetric(
                                  vertical: 12,
                                ),
                                decoration: BoxDecoration(
                                  color: currentTabIndex == i
                                      ? AppColor.white
                                      : Colors.transparent,
                                  borderRadius: BorderRadius.circular(25),
                                ),
                                child: Text(
                                  ['Spin Wheel', 'Daftar Hadiah', 'Riwayat'][i],
                                  textAlign: TextAlign.center,
                                  style: AppStyle.md.copyWith(
                                    fontWeight: FontWeight.bold,
                                    color: currentTabIndex == i
                                        ? AppColor.primary
                                        : AppColor.textWhite,
                                  ),
                                ),
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),

                  const SizedBox(height: 20),

                  // Content Area
                  Expanded(
                    child: currentTabIndex == 0
                        ? _buildMainContent()
                        : currentTabIndex == 1
                        ? _buildPrizeListContent()
                        : _buildHistoryContent(),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildMainContent() {
    return Column(
      children: [
        // User Info Card
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: AppColor.white,
            borderRadius: BorderRadius.circular(15),
            boxShadow: [
              BoxShadow(
                color: AppColor.black.withOpacity(0.1),
                blurRadius: 10,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              BlocBuilder<AuthBloc, AuthState>(
                builder: (context, auth) {
                  return Row(
                    children: [
                      Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          color: AppColor.primary,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Center(
                          child: Text(
                            'G',
                            style: AppStyle.lg.copyWith(
                              color: AppColor.textWhite,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(width: 12),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            auth.user.name,
                            style: AppStyle.lg.copyWith(
                              fontWeight: FontWeight.bold,
                              color: AppColor.textPrimary,
                            ),
                          ),
                          Text(
                            auth.user.phoneNumber,
                            style: AppStyle.sm.copyWith(
                              color: AppColor.textSecondary,
                            ),
                          ),
                        ],
                      ),
                    ],
                  );
                },
              ),
              Row(
                children: [
                  Container(
                    width: 20,
                    height: 20,
                    decoration: BoxDecoration(
                      color: AppColor.warning,
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.circle,
                      size: 12,
                      color: AppColor.textWhite,
                    ),
                  ),
                  const SizedBox(width: 8),
                  Text(
                    'Token: $tokens',
                    style: AppStyle.lg.copyWith(
                      fontWeight: FontWeight.bold,
                      color: AppColor.textPrimary,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),

        Text(
          resultText,
          style: AppStyle.md.copyWith(color: AppColor.textWhite),
        ),
        const SizedBox(height: 20),

        // Wheel Section
        Expanded(
          child: Center(
            child: gamePrizes.isEmpty
                ? SpinKitFadingCircle(color: AppColor.textWhite, size: 36)
                : Stack(
                    alignment: Alignment.center,
                    children: [
                      // Glow Effect
                      AnimatedBuilder(
                        animation: _glowController,
                        builder: (context, child) => Container(
                          width: 340,
                          height: 340,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            boxShadow: [
                              BoxShadow(
                                color: AppColor.white.withOpacity(
                                  0.3 + 0.2 * _glowController.value,
                                ),
                                blurRadius: 40,
                                spreadRadius: 10,
                              ),
                            ],
                          ),
                        ),
                      ),

                      // Spinning Wheel
                      AnimatedBuilder(
                        animation: isSpinning
                            ? _rotationController
                            : _idleRotationController,
                        builder: (context, child) {
                          double rotationAngle = isSpinning
                              ? (_spinAnimation?.value ?? currentRotation)
                              : (currentRotation +
                                    (_idleRotationAnimation?.value ?? 0.0));

                          return Transform.rotate(
                            angle: rotationAngle,
                            child: CustomPaint(
                              size: const Size(320, 320),
                              painter: WheelPainter(
                                gamePrizes: gamePrizes,
                                getPrizeColor: _getPrizeColor,
                              ),
                            ),
                          );
                        },
                      ),

                      // Spin Button
                      AnimatedBuilder(
                        animation:
                            _pulseAnimation ??
                            const AlwaysStoppedAnimation(1.0),
                        builder: (context, child) => Transform.scale(
                          scale: _pulseAnimation?.value ?? 1.0,
                          child: Container(
                            width: 100,
                            height: 100,
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                colors: [AppColor.warning, AppColor.warning],
                              ),
                              shape: BoxShape.circle,
                              boxShadow: [
                                BoxShadow(
                                  color: AppColor.black.withOpacity(0.3),
                                  blurRadius: 15,
                                  offset: const Offset(0, 6),
                                ),
                                BoxShadow(
                                  color: AppColor.warning.withOpacity(0.5),
                                  blurRadius: 20,
                                  spreadRadius:
                                      (_pulseAnimation?.value ?? 1.0) * 5,
                                ),
                              ],
                            ),
                            child: Material(
                              color: Colors.transparent,
                              child: InkWell(
                                borderRadius: BorderRadius.circular(50),
                                onTap: _spinWheel,
                                child: Center(
                                  child: Text(
                                    'SPIN',
                                    style: AppStyle.lg.copyWith(
                                      color: AppColor.textWhite,
                                      fontWeight: FontWeight.bold,
                                      letterSpacing: 1,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),

                      // Pointer
                      Positioned(
                        top: 30,
                        child: Container(
                          width: 0,
                          height: 0,
                          decoration: BoxDecoration(
                            border: Border(
                              left: BorderSide(
                                width: 15,
                                color: Colors.transparent,
                              ),
                              right: BorderSide(
                                width: 15,
                                color: Colors.transparent,
                              ),
                              bottom: BorderSide(
                                width: 30,
                                color: AppColor.error,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
          ),
        ),

        // Bottom Banner
        Container(
          margin: const EdgeInsets.all(20),
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [AppColor.warning, AppColor.warning],
            ),
            borderRadius: BorderRadius.circular(15),
          ),
          child: Text(
            'Spin 30x lagi buat mainin spesial spin',
            textAlign: TextAlign.center,
            style: AppStyle.lg.copyWith(
              color: AppColor.textWhite,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildPrizeListContent() {
    return Container(
      margin: const EdgeInsets.all(20),
      child: Column(
        children: [
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppColor.white,
              borderRadius: BorderRadius.circular(15),
              boxShadow: [
                BoxShadow(
                  color: AppColor.black.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Text(
              'Daftar Hadiah',
              style: AppStyle.h6.copyWith(
                fontWeight: FontWeight.bold,
                color: AppColor.textPrimary,
              ),
            ),
          ),
          const SizedBox(height: 20),
          Expanded(
            child: gamePrizes.isEmpty
                ? Center(
                    child: SpinKitFadingCircle(
                      color: AppColor.white.withOpacity(0.7),
                      size: 36,
                    ),
                  )
                : ListView.builder(
                    itemCount: gamePrizes.length,
                    itemBuilder: (context, index) {
                      final prize = gamePrizes[index];
                      return Container(
                        margin: const EdgeInsets.only(bottom: 12),
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: AppColor.white,
                          borderRadius: BorderRadius.circular(12),
                          boxShadow: [
                            BoxShadow(
                              color: AppColor.black.withOpacity(0.05),
                              blurRadius: 5,
                              offset: const Offset(0, 2),
                            ),
                          ],
                        ),
                        child: Row(
                          children: [
                            Container(
                              width: 50,
                              height: 50,
                              decoration: BoxDecoration(
                                color: _getPrizeColor(prize, index),
                                borderRadius: BorderRadius.circular(25),
                              ),
                              child: Icon(
                                Icons.card_giftcard,
                                color: AppColor.white,
                                size: 24,
                              ),
                            ),
                            const SizedBox(width: 16),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    prize.name,
                                    style: AppStyle.lg.copyWith(
                                      fontWeight: FontWeight.bold,
                                      color: AppColor.textPrimary,
                                    ),
                                  ),
                                  Text(
                                    'Nilai: ${prize.metadata['value'] ?? prize.weight}',
                                    style: AppStyle.sm.copyWith(
                                      color: AppColor.textSecondary,
                                    ),
                                  ),
                                  Text(
                                    'Stok: ${prize.stock}/${prize.maxStock}',
                                    style: AppStyle.xs.copyWith(
                                      color: prize.stock > 0
                                          ? AppColor.success
                                          : AppColor.error,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 6,
                              ),
                              decoration: BoxDecoration(
                                color: _getPrizeColor(
                                  prize,
                                  index,
                                ).withOpacity(0.1),
                                borderRadius: BorderRadius.circular(15),
                              ),
                              child: Text(
                                'Weight: ${prize.weight}',
                                style: AppStyle.xs.copyWith(
                                  color: _getPrizeColor(prize, index),
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }

  Widget _buildHistoryContent() {
    return Container(
      margin: const EdgeInsets.all(20),
      child: Column(
        children: [
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppColor.white,
              borderRadius: BorderRadius.circular(15),
              boxShadow: [
                BoxShadow(
                  color: AppColor.black.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Text(
              'Riwayat Hadiah',
              style: AppStyle.h6.copyWith(
                fontWeight: FontWeight.bold,
                color: AppColor.textPrimary,
              ),
            ),
          ),
          const SizedBox(height: 20),
          Expanded(
            child: prizeHistory.isEmpty
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.history,
                          size: 80,
                          color: AppColor.white.withOpacity(0.5),
                        ),
                        const SizedBox(height: 16),
                        Text(
                          'Belum ada riwayat spin',
                          style: AppStyle.lg.copyWith(
                            color: AppColor.white.withOpacity(0.7),
                          ),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          'Mulai spin untuk melihat riwayat hadiah',
                          style: AppStyle.md.copyWith(
                            color: AppColor.white.withOpacity(0.5),
                          ),
                        ),
                      ],
                    ),
                  )
                : ListView.builder(
                    itemCount: prizeHistory.length,
                    itemBuilder: (context, index) {
                      final history = prizeHistory[index];
                      return Container(
                        margin: const EdgeInsets.only(bottom: 12),
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: AppColor.white,
                          borderRadius: BorderRadius.circular(12),
                          boxShadow: [
                            BoxShadow(
                              color: AppColor.black.withOpacity(0.05),
                              blurRadius: 5,
                              offset: const Offset(0, 2),
                            ),
                          ],
                        ),
                        child: Row(
                          children: [
                            Container(
                              width: 50,
                              height: 50,
                              decoration: BoxDecoration(
                                color: history.color,
                                borderRadius: BorderRadius.circular(25),
                              ),
                              child: Icon(
                                history.icon,
                                color: AppColor.white,
                                size: 24,
                              ),
                            ),
                            const SizedBox(width: 16),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    history.prize,
                                    style: AppStyle.lg.copyWith(
                                      fontWeight: FontWeight.bold,
                                      color: AppColor.textPrimary,
                                    ),
                                  ),
                                  Text(
                                    '${history.dateTime.day}/${history.dateTime.month}/${history.dateTime.year} ${history.dateTime.hour.toString().padLeft(2, '0')}:${history.dateTime.minute.toString().padLeft(2, '0')}',
                                    style: AppStyle.sm.copyWith(
                                      color: AppColor.textSecondary,
                                    ),
                                  ),
                                  if (history.gamePrizeId != null)
                                    Text(
                                      'ID: ${history.gamePrizeId}',
                                      style: AppStyle.xs.copyWith(
                                        color: AppColor.textSecondary
                                            .withOpacity(0.7),
                                      ),
                                    ),
                                ],
                              ),
                            ),
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 6,
                              ),
                              decoration: BoxDecoration(
                                color: AppColor.success.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(15),
                              ),
                              child: Text(
                                'Menang',
                                style: AppStyle.sm.copyWith(
                                  color: AppColor.success,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }
}
