import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';

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

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

  @override
  State<DrawDetailPage> createState() => _DrawDetailPageState();
}

class _DrawDetailPageState extends State<DrawDetailPage>
    with TickerProviderStateMixin {
  late AnimationController _fadeController;
  late AnimationController _slideController;
  late AnimationController _scaleController;

  late Animation<double> _fadeAnimation;
  late Animation<double> _scaleAnimation;

  final CarouselSliderController _carouselController =
      CarouselSliderController();
  final CarouselSliderController _numberCarouselController =
      CarouselSliderController();
  final ScrollController _scrollController = ScrollController();

  int _currentBannerIndex = 0;
  int _currentNumberIndex = 0;
  bool _isCollapsed = false;

  List<String> lotteryNumbers = ['849302', '156789', '973421', '642853'];
  bool isOngoing = true;
  DateTime endTime = DateTime.now().add(Duration(hours: 2, minutes: 30));

  final List<PrizeModel> prizes = [
    PrizeModel(
      title: 'HADIAH UTAMA',
      description: '3KG Emas Batangan',
      icon: Icons.stars_rounded,
      color: AppColor.warning,
      isMain: true,
    ),
    PrizeModel(
      title: 'HADIAH KE-2',
      description: '1KG Emas Batangan',
      icon: Icons.diamond_outlined,
      color: AppColor.primary,
      isMain: false,
    ),
    PrizeModel(
      title: 'HADIAH KE-3',
      description: 'Voucher Belanja 10 Juta',
      icon: Icons.card_giftcard_outlined,
      color: AppColor.success,
      isMain: false,
    ),
    PrizeModel(
      title: 'HADIAH HIBURAN',
      description: 'Voucher Belanja 1 Juta',
      icon: Icons.local_activity_outlined,
      color: AppColor.info,
      isMain: false,
    ),
  ];

  final List<BannerModel> banners = [
    BannerModel(
      imageUrl: 'https://picsum.photos/800/400?random=1',
      title: 'Undian Berhadiah Emas',
    ),
    BannerModel(
      imageUrl: 'https://picsum.photos/800/400?random=2',
      title: 'Kesempatan Menang 3KG Emas',
    ),
    BannerModel(
      imageUrl: 'https://picsum.photos/800/400?random=3',
      title: 'Undian Harian Terbesar',
    ),
  ];

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

    _scrollController.addListener(() {
      bool isCollapsed =
          _scrollController.hasClients &&
          _scrollController.offset > (280 - kToolbarHeight);
      if (this._isCollapsed != isCollapsed) {
        setState(() {
          this._isCollapsed = isCollapsed;
        });
      }
    });

    _fadeController = AnimationController(
      duration: Duration(milliseconds: 1200),
      vsync: this,
    );
    _slideController = AnimationController(
      duration: Duration(milliseconds: 800),
      vsync: this,
    );
    _scaleController = AnimationController(
      duration: Duration(milliseconds: 1000),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _fadeController, curve: Curves.easeInOut),
    );
    _scaleAnimation = Tween<double>(begin: 0.8, end: 1.0).animate(
      CurvedAnimation(parent: _scaleController, 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();
  }

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

  Widget _buildCard({required Widget child}) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20),
      padding: EdgeInsets.all(24),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [AppColor.primary, AppColor.primary.withOpacity(0.8)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(24),
        boxShadow: [
          BoxShadow(
            color: AppColor.black.withOpacity(0.08),
            blurRadius: 30,
            spreadRadius: 0,
            offset: Offset(0, 15),
          ),
        ],
      ),
      child: child,
    );
  }

  void _showFullImage(String imageUrl, String title) {
    int dialogCurrentIndex = banners.indexWhere(
      (banner) => banner.imageUrl == imageUrl,
    );
    if (dialogCurrentIndex == -1) dialogCurrentIndex = 0;

    final CarouselSliderController dialogCarouselController =
        CarouselSliderController();

    showDialog(
      context: context,
      useSafeArea: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setDialogState) {
            return Material(
              type: MaterialType.transparency,
              child: Container(
                width: double.infinity,
                height: MediaQuery.of(context).size.height,
                color: Colors.black.withOpacity(0.9),
                child: SafeArea(
                  child: Column(
                    children: [
                      // Header dengan close button
                      Container(
                        padding: EdgeInsets.all(16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              'Gallery',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 18,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            GestureDetector(
                              onTap: () => Navigator.of(context).pop(),
                              child: Container(
                                padding: EdgeInsets.all(8),
                                decoration: BoxDecoration(
                                  color: Colors.white.withOpacity(0.2),
                                  shape: BoxShape.circle,
                                ),
                                child: Icon(
                                  Icons.close,
                                  color: Colors.white,
                                  size: 24,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      // Main carousel
                      Expanded(
                        child: CarouselSlider.builder(
                          itemCount: banners.length,
                          carouselController: dialogCarouselController,
                          options: CarouselOptions(
                            height: double.infinity,
                            viewportFraction: 1.0,
                            enableInfiniteScroll: false,
                            initialPage: dialogCurrentIndex,
                            onPageChanged: (index, reason) {
                              setDialogState(() {
                                dialogCurrentIndex = index;
                              });
                            },
                          ),
                          itemBuilder: (context, index, realIndex) {
                            return Container(
                              margin: EdgeInsets.symmetric(horizontal: 16),
                              child: InteractiveViewer(
                                minScale: 0.8,
                                maxScale: 3.0,
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(12),
                                  child: Image.network(
                                    banners[index].imageUrl,
                                    fit: BoxFit.contain,
                                    width: double.infinity,
                                    loadingBuilder: (context, child, progress) {
                                      if (progress == null) return child;
                                      return Container(
                                        decoration: BoxDecoration(
                                          color: Colors.grey[800],
                                          borderRadius: BorderRadius.circular(
                                            12,
                                          ),
                                        ),
                                        child: Center(
                                          child: CircularProgressIndicator(
                                            valueColor:
                                                AlwaysStoppedAnimation<Color>(
                                                  Colors.white,
                                                ),
                                          ),
                                        ),
                                      );
                                    },
                                    errorBuilder: (context, error, stackTrace) {
                                      return Container(
                                        decoration: BoxDecoration(
                                          color: Colors.grey[800],
                                          borderRadius: BorderRadius.circular(
                                            12,
                                          ),
                                        ),
                                        child: Center(
                                          child: Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: [
                                              Icon(
                                                Icons.error_outline,
                                                color: Colors.white,
                                                size: 48,
                                              ),
                                              SizedBox(height: 8),
                                              Text(
                                                'Error loading image',
                                                style: TextStyle(
                                                  color: Colors.white,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      );
                                    },
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                      ),

                      // Bottom area
                      Container(
                        padding: EdgeInsets.all(16),
                        child: Column(
                          children: [
                            // Title
                            Text(
                              banners[dialogCurrentIndex].title,
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                              textAlign: TextAlign.center,
                            ),

                            SizedBox(height: 16),

                            // Thumbnails
                            SizedBox(
                              height: 60,
                              child: ListView.builder(
                                scrollDirection: Axis.horizontal,
                                itemCount: banners.length,
                                itemBuilder: (context, index) {
                                  bool isActive = dialogCurrentIndex == index;
                                  return GestureDetector(
                                    onTap: () {
                                      setDialogState(() {
                                        dialogCurrentIndex = index;
                                      });
                                      dialogCarouselController.animateToPage(
                                        index,
                                      );
                                    },
                                    child: Container(
                                      width: 80,
                                      height: 60,
                                      margin: EdgeInsets.symmetric(
                                        horizontal: 4,
                                      ),
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(8),
                                        border: Border.all(
                                          color: isActive
                                              ? Colors.white
                                              : Colors.white.withOpacity(0.3),
                                          width: isActive ? 3 : 1,
                                        ),
                                      ),
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.circular(6),
                                        child: Stack(
                                          children: [
                                            Image.network(
                                              banners[index].imageUrl,
                                              width: 80,
                                              height: 60,
                                              fit: BoxFit.cover,
                                            ),
                                            if (!isActive)
                                              Container(
                                                color: Colors.black.withOpacity(
                                                  0.5,
                                                ),
                                              ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  );
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildLotteryCard() {
    return ScaleTransition(
      scale: _scaleAnimation,
      child: _buildCard(
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                color: isOngoing
                    ? AppColor.warning.withOpacity(0.2)
                    : AppColor.white.withOpacity(0.2),
                borderRadius: BorderRadius.circular(20),
              ),
              child: Text(
                isOngoing
                    ? '🕐 UNDIAN SEDANG BERLANGSUNG'
                    : 'NOMOR UNDIAN GLOBAL',
                style: TextStyle(
                  color: isOngoing ? AppColor.warning : AppColor.white,
                  fontWeight: FontWeight.w700,
                  fontSize: 11,
                  letterSpacing: 1,
                ),
              ),
            ),
            SizedBox(height: 20),
            if (isOngoing) _buildCountdown() else _buildNumberCarousel(),
          ],
        ),
      ),
    );
  }

  Widget _buildCountdown() {
    return StreamBuilder<DateTime>(
      stream: Stream.periodic(Duration(seconds: 1), (_) => DateTime.now()),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return Container();

        final now = snapshot.data!;
        final difference = endTime.difference(now);

        if (difference.isNegative) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            setState(() {
              isOngoing = false;
            });
          });
          return Container();
        }

        final hours = difference.inHours;
        final minutes = difference.inMinutes % 60;
        final seconds = difference.inSeconds % 60;

        return Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 24),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                AppColor.warning.withOpacity(0.2),
                AppColor.warning.withOpacity(0.1),
              ],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            borderRadius: BorderRadius.circular(16),
            border: Border.all(
              color: AppColor.warning.withOpacity(0.3),
              width: 1,
            ),
          ),
          child: Column(
            children: [
              Text(
                'Pengundian dimulai dalam:',
                style: TextStyle(
                  color: AppColor.warning,
                  fontWeight: FontWeight.w600,
                  fontSize: 14,
                ),
              ),
              SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildTimeUnit(hours.toString().padLeft(2, '0'), 'JAM'),
                  Text(
                    ':',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: AppColor.warning,
                    ),
                  ),
                  _buildTimeUnit(minutes.toString().padLeft(2, '0'), 'MENIT'),
                  Text(
                    ':',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: AppColor.warning,
                    ),
                  ),
                  _buildTimeUnit(seconds.toString().padLeft(2, '0'), 'DETIK'),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildTimeUnit(String time, String label) {
    return Column(
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          decoration: BoxDecoration(
            color: AppColor.warning,
            borderRadius: BorderRadius.circular(8),
            boxShadow: [
              BoxShadow(
                color: AppColor.warning.withOpacity(0.3),
                blurRadius: 8,
                offset: Offset(0, 4),
              ),
            ],
          ),
          child: Text(
            time,
            style: TextStyle(
              color: AppColor.white,
              fontSize: 24,
              fontWeight: FontWeight.w900,
            ),
          ),
        ),
        SizedBox(height: 4),
        Text(
          label,
          style: TextStyle(
            color: AppColor.warning,
            fontWeight: FontWeight.w600,
            fontSize: 10,
          ),
        ),
      ],
    );
  }

  Widget _buildNumberCarousel() {
    return Column(
      children: [
        Container(
          height: 80,
          child: CarouselSlider.builder(
            carouselController: _numberCarouselController,
            itemCount: lotteryNumbers.length,
            options: CarouselOptions(
              height: 80,
              viewportFraction: 1.0,
              enableInfiniteScroll: true,
              autoPlay: false,
              onPageChanged: (index, reason) {
                setState(() => _currentNumberIndex = index);
              },
            ),
            itemBuilder: (context, index, realIndex) {
              return Container(
                width: double.infinity,
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 16),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      AppColor.white.withOpacity(0.2),
                      AppColor.white.withOpacity(0.1),
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: BorderRadius.circular(16),
                  border: Border.all(
                    color: AppColor.white.withOpacity(0.3),
                    width: 1,
                  ),
                ),
                child: Center(
                  child: Text(
                    lotteryNumbers[index],
                    style: TextStyle(
                      color: AppColor.white,
                      fontSize: 42,
                      fontWeight: FontWeight.w900,
                      letterSpacing: 12,
                      height: 1.0,
                    ),
                  ),
                ),
              );
            },
          ),
        ),
        SizedBox(height: 16),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: lotteryNumbers.asMap().entries.map((entry) {
            return GestureDetector(
              onTap: () => _numberCarouselController.animateToPage(entry.key),
              child: Container(
                width: _currentNumberIndex == entry.key ? 24 : 8,
                height: 8,
                margin: EdgeInsets.symmetric(horizontal: 4),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                  color: _currentNumberIndex == entry.key
                      ? AppColor.white
                      : AppColor.white.withOpacity(0.4),
                ),
              ),
            );
          }).toList(),
        ),
        SizedBox(height: 12),
        Text(
          '${_currentNumberIndex + 1} dari ${lotteryNumbers.length} nomor',
          style: TextStyle(
            color: AppColor.white.withOpacity(0.8),
            fontWeight: FontWeight.w500,
            fontSize: 11,
          ),
        ),
      ],
    );
  }

  Widget _buildPrizeCard() {
    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: _buildCard(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'DAFTAR HADIAH',
              style: TextStyle(
                color: AppColor.white.withOpacity(0.9),
                fontWeight: FontWeight.w700,
                fontSize: 14,
                letterSpacing: 1.5,
              ),
            ),
            SizedBox(height: 20),
            ...prizes.map((prize) => _buildPrizeItem(prize)).toList(),
          ],
        ),
      ),
    );
  }

  Widget _buildPrizeItem(PrizeModel prize) {
    return Container(
      margin: EdgeInsets.only(bottom: 16),
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            prize.color.withOpacity(prize.isMain ? 0.3 : 0.2),
            prize.color.withOpacity(prize.isMain ? 0.2 : 0.1),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: prize.color.withOpacity(prize.isMain ? 0.5 : 0.3),
          width: prize.isMain ? 2 : 1,
        ),
      ),
      child: Row(
        children: [
          Container(
            padding: EdgeInsets.all(prize.isMain ? 12 : 10),
            decoration: BoxDecoration(
              color: prize.color,
              borderRadius: BorderRadius.circular(12),
              boxShadow: prize.isMain
                  ? [
                      BoxShadow(
                        color: prize.color.withOpacity(0.3),
                        blurRadius: 10,
                        offset: Offset(0, 4),
                      ),
                    ]
                  : null,
            ),
            child: Icon(
              prize.icon,
              color: AppColor.white,
              size: prize.isMain ? 24 : 20,
            ),
          ),
          SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  prize.title,
                  style: TextStyle(
                    color: prize.color,
                    fontWeight: FontWeight.w700,
                    fontSize: 11,
                    letterSpacing: 0.5,
                  ),
                ),
                SizedBox(height: 4),
                Text(
                  prize.description,
                  style: TextStyle(
                    color: AppColor.white,
                    fontWeight: prize.isMain
                        ? FontWeight.w700
                        : FontWeight.w600,
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          ),
          if (prize.isMain)
            Container(
              padding: EdgeInsets.all(6),
              decoration: BoxDecoration(
                color: prize.color.withOpacity(0.2),
                shape: BoxShape.circle,
              ),
              child: Icon(Icons.star, color: prize.color, size: 16),
            ),
        ],
      ),
    );
  }

  Widget _buildShoppingCard() {
    return SlideTransition(
      position: Tween<Offset>(begin: Offset(0, 0.8), end: Offset.zero).animate(
        CurvedAnimation(
          parent: _slideController,
          curve: Interval(0.5, 1.0, curve: Curves.easeOutCubic),
        ),
      ),
      child: _buildCard(
        child: Column(
          children: [
            Row(
              children: [
                Container(
                  padding: EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: AppColor.white.withOpacity(0.2),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Icon(
                    Icons.shopping_bag_outlined,
                    color: AppColor.white,
                    size: 24,
                  ),
                ),
                SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Perbesar Peluang Menang!',
                        style: TextStyle(
                          color: AppColor.white,
                          fontWeight: FontWeight.w700,
                          fontSize: 16,
                        ),
                      ),
                      SizedBox(height: 4),
                      Text(
                        'Belanja sekarang untuk ticket tambahan',
                        style: TextStyle(
                          color: AppColor.white.withOpacity(0.8),
                          fontWeight: FontWeight.w500,
                          fontSize: 11,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: 20),
            Container(
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: AppColor.white.withOpacity(0.1),
                borderRadius: BorderRadius.circular(16),
                border: Border.all(
                  color: AppColor.white.withOpacity(0.2),
                  width: 1,
                ),
              ),
              child: Column(
                children: [
                  _buildBenefit('🎫', 'Setiap Rp 100K = 1 ticket undian'),
                  SizedBox(height: 12),
                  _buildBenefit(
                    '⚡',
                    'Semakin banyak belanja, semakin berpeluang',
                  ),
                  SizedBox(height: 12),
                  _buildBenefit('🏆', 'Kesempatan menang hingga 3KG emas!'),
                ],
              ),
            ),
            SizedBox(height: 20),
            Container(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('Mengarahkan ke halaman belanja...'),
                      backgroundColor: AppColor.success,
                      behavior: SnackBarBehavior.floating,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                  );
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColor.white,
                  foregroundColor: AppColor.primary,
                  padding: EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                  elevation: 0,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.shopping_cart_outlined, size: 20),
                    SizedBox(width: 12),
                    Text(
                      'Mulai Belanja Sekarang',
                      style: TextStyle(
                        fontWeight: FontWeight.w700,
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBenefit(String icon, String text) {
    return Row(
      children: [
        Text(icon, style: TextStyle(fontSize: 16)),
        SizedBox(width: 12),
        Expanded(
          child: Text(
            text,
            style: TextStyle(
              color: AppColor.white.withOpacity(0.9),
              fontWeight: FontWeight.w500,
              fontSize: 11,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildTermsAndConditions() {
    return SlideTransition(
      position: Tween<Offset>(begin: Offset(0, 1.0), end: Offset.zero).animate(
        CurvedAnimation(
          parent: _slideController,
          curve: Interval(0.7, 1.0, curve: Curves.easeOutCubic),
        ),
      ),
      child: _buildCard(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.description_outlined,
                  color: AppColor.white.withOpacity(0.9),
                  size: 20,
                ),
                SizedBox(width: 12),
                Text(
                  'Syarat & Ketentuan',
                  style: TextStyle(
                    color: AppColor.white,
                    fontWeight: FontWeight.w700,
                    fontSize: 16,
                  ),
                ),
              ],
            ),
            SizedBox(height: 20),
            _buildTermItem(
              '1.',
              'Undian berlaku untuk seluruh pelanggan yang berbelanja minimal Rp 100.000',
            ),
            _buildTermItem(
              '2.',
              'Setiap pembelian Rp 100.000 mendapat 1 nomor undian otomatis',
            ),
            _buildTermItem(
              '3.',
              'Pengundian dilakukan secara live streaming setiap hari pukul 20:00 WIB',
            ),
            _buildTermItem(
              '4.',
              'Pemenang akan dihubungi maksimal 24 jam setelah pengundian',
            ),
            _buildTermItem(
              '5.',
              'Hadiah tidak dapat diuangkan atau dipindahtangankan',
            ),
            _buildTermItem(
              '6.',
              'Keputusan panitia adalah final dan tidak dapat diganggu gugat',
            ),
            SizedBox(height: 20),
            Container(
              padding: EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: AppColor.white.withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Row(
                children: [
                  Icon(Icons.info_outline, color: AppColor.white, size: 16),
                  SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      'Untuk informasi lebih lanjut, hubungi customer service kami',
                      style: TextStyle(
                        color: AppColor.white.withOpacity(0.9),
                        fontWeight: FontWeight.w500,
                        fontSize: 11,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTermItem(String number, String text) {
    return Padding(
      padding: EdgeInsets.only(bottom: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 24,
            child: Text(
              number,
              style: TextStyle(
                color: AppColor.white,
                fontWeight: FontWeight.w600,
                fontSize: 11,
              ),
            ),
          ),
          SizedBox(width: 12),
          Expanded(
            child: Text(
              text,
              style: TextStyle(
                color: AppColor.white.withOpacity(0.9),
                fontWeight: FontWeight.w500,
                fontSize: 11,
                height: 1.4,
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        controller: _scrollController,
        physics: BouncingScrollPhysics(),
        slivers: [
          SliverAppBar(
            expandedHeight: 280,
            floating: false,
            pinned: true,
            backgroundColor: AppColor.surface,
            leading: Container(
              margin: EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.3),
                borderRadius: BorderRadius.circular(20),
              ),
              child: IconButton(
                icon: Icon(Icons.arrow_back, color: Colors.white),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ),
            flexibleSpace: FlexibleSpaceBar(
              title: AnimatedOpacity(
                opacity: _isCollapsed ? 1.0 : 0.0,
                duration: Duration(milliseconds: 200),
                child: Text(
                  "Undian",
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    color: AppColor.textPrimary,
                    fontSize: 18,
                  ),
                ),
              ),
              titlePadding: EdgeInsets.only(left: 72, bottom: 16),
              collapseMode: CollapseMode.parallax,
              background: Stack(
                children: [
                  Positioned.fill(
                    child: CarouselSlider.builder(
                      carouselController: _carouselController,
                      itemCount: banners.length,
                      options: CarouselOptions(
                        height: double.infinity,
                        viewportFraction: 1.0,
                        autoPlay: true,
                        autoPlayInterval: Duration(seconds: 4),
                        autoPlayAnimationDuration: Duration(milliseconds: 800),
                        onPageChanged: (index, reason) {
                          setState(() => _currentBannerIndex = index);
                        },
                      ),
                      itemBuilder: (context, index, realIndex) {
                        final banner = banners[index];
                        return GestureDetector(
                          onTap: () =>
                              _showFullImage(banner.imageUrl, banner.title),
                          child: AppNetworkImage(url: banner.imageUrl),
                        );
                      },
                    ),
                  ),

                  Positioned(
                    bottom: 20,
                    left: 0,
                    right: 0,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: banners.asMap().entries.map((entry) {
                        return GestureDetector(
                          onTap: () =>
                              _carouselController.animateToPage(entry.key),
                          child: Container(
                            width: _currentBannerIndex == entry.key ? 24 : 8,
                            height: 8,
                            margin: EdgeInsets.symmetric(horizontal: 4),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(4),
                              color: _currentBannerIndex == entry.key
                                  ? Colors.white
                                  : Colors.white.withOpacity(0.4),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                  ),
                ],
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: AppColor.primaryGradient,
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
              ),
              child: FadeTransition(
                opacity: _fadeAnimation,
                child: Column(
                  children: [
                    SizedBox(height: 20),
                    _buildLotteryCard(),
                    SizedBox(height: 20),
                    _buildPrizeCard(),
                    SizedBox(height: 20),
                    if (isOngoing) _buildShoppingCard(),
                    if (isOngoing) SizedBox(height: 20),
                    _buildTermsAndConditions(),
                    SizedBox(height: 40),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class PrizeModel {
  final String title;
  final String description;
  final IconData icon;
  final Color color;
  final bool isMain;

  PrizeModel({
    required this.title,
    required this.description,
    required this.icon,
    required this.color,
    this.isMain = false,
  });
}

class BannerModel {
  final String imageUrl;
  final String title;

  BannerModel({required this.imageUrl, required this.title});
}
