import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'home_page.dart';

class OnboardingScreen extends StatefulWidget {
  const OnboardingScreen({super.key});

  @override
  State<OnboardingScreen> createState() => _OnboardingScreenState();
}

class _OnboardingScreenState extends State<OnboardingScreen> {
  final PageController _controller = PageController();
  int _currentIndex = 0;
  Timer? _timer;
  double _imageOpacity = 0.0;
  double _imageScale = 0.8;

  final List<Map<String, String>> onboardingData = [
    {
      'title': 'Selamat datang di',
      'highlight': 'ClassiFragis',
      'description':
          'Selamat datang di ClassiFragis! Aplikasi Identifikasi Kesegaran Stroberi yang siap mempercepat waktu Anda.',
      'image': 'assets/onboard1.png',
    },
    {
      'title': 'Mudah dengan menggunakan',
      'highlight': 'Android',
      'description':
          'Di sini Kamu dapat merasakan kemudahan dalam mengidentifikasi stroberi dengan menggunakan kamera Android langsung tanpa harus ribet.',
      'image': 'assets/onboard2.png',
    },
    {
      'title': 'Mendapatkan hasil yang cukup',
      'highlight': 'Akurat',
      'description':
          'Dengan menggunakan aplikasi ini, Anda dapat dengan mudah memperoleh hasil yang cukup Akurat.',
      'image': 'assets/onboard3.png',
    },
  ];

  @override
  void initState() {
    super.initState();
    _startAutoSlide();
    _animateImage();
  }

  void _startAutoSlide() {
    _timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      if (_currentIndex < onboardingData.length - 1) {
        _currentIndex++;
      } else {
        _currentIndex = 0;
      }
      _controller.animateToPage(
        _currentIndex,
        duration: const Duration(milliseconds: 500),
        curve: Curves.easeInOut,
      );
    });
  }

  void _animateImage() {
    setState(() {
      _imageOpacity = 0.0;
      _imageScale = 0.8;
    });
    Future.delayed(const Duration(milliseconds: 100), () {
      setState(() {
        _imageOpacity = 1.0;
        _imageScale = 1.0;
      });
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white, // Latar belakang putih
      body: ScreenUtilInit(
        designSize: const Size(375, 812),
        builder: (context, child) {
          return Column(
            children: [
              Expanded(
                child: PageView.builder(
                  controller: _controller,
                  itemCount: onboardingData.length,
                  onPageChanged: (index) {
                    setState(() {
                      _currentIndex = index;
                    });
                    _animateImage(); // Animasi ulang saat halaman berubah
                  },
                  itemBuilder: (context, index) {
                    final data = onboardingData[index];
                    return Padding(
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            data['title']!,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 22.sp,
                              fontWeight: FontWeight.w500,
                              color: Colors.black87,
                              shadows: const [
                                Shadow(
                                  blurRadius: 5.0,
                                  color: Colors.black12,
                                  offset: Offset(1.0, 1.0),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(height: 5.h),
                          Text(
                            data['highlight']!,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 26.sp,
                              fontWeight: FontWeight.bold,
                              color: const Color(0xFF891A2D),
                              shadows: const [
                                Shadow(
                                  blurRadius: 5.0,
                                  color: Colors.black12,
                                  offset: Offset(1.0, 1.0),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(height: 30.h),
                          AnimatedOpacity(
                            opacity: _imageOpacity,
                            duration: const Duration(milliseconds: 500),
                            child: AnimatedScale(
                              scale: _imageScale,
                              duration: const Duration(milliseconds: 500),
                              curve: Curves.easeOutBack,
                              child: Image.asset(
                                data['image']!,
                                height: 300.h,
                              ),
                            ),
                          ),
                          SizedBox(height: 30.h),
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 20.w),
                            child: Text(
                              data['description']!,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 16.sp,
                                color: Colors.black87,
                                height: 1.5,
                              ),
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: List.generate(
                  onboardingData.length,
                  (index) => AnimatedContainer(
                    duration: const Duration(milliseconds: 300),
                    margin: EdgeInsets.symmetric(horizontal: 5.w),
                    width: _currentIndex == index ? 24.w : 10.w,
                    height: 10.h,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(5.r),
                      color: _currentIndex == index
                          ? const Color(0xFF891A2D)
                          : Colors.grey[300],
                    ),
                  ),
                ),
              ),
              SizedBox(height: 30.h),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 15.h),
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF891A2D),
                    foregroundColor: Colors.white.withOpacity(0.1),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(15.r),
                    ),
                    padding: EdgeInsets.symmetric(vertical: 16.h),
                    elevation: 5,
                    shadowColor: Colors.black26,
                  ),
                  onPressed: () {
                    _timer?.cancel();
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => const HomePage()),
                    );
                  },
                  child: Center(
                    child: Text(
                      'Mulai',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18.sp,
                        fontWeight: FontWeight.bold,
                        letterSpacing: 0.5,
                      ),
                    ),
                  ),
                ),
              ),
              SizedBox(height: 30.h),
            ],
          );
        },
      ),
    );
  }
}
