import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sistem_pakarcabai/pages/diagnosis_page.dart';
import 'package:infinite_carousel/infinite_carousel.dart';

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

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

class _OnboardingScreenState extends State<OnboardingScreen> {
  int currentIndex = 0;
  late InfiniteScrollController _controller;
  Timer? _autoSlideTimer;

  final List<Map<String, String>> onboardingData = [
    {
      "image": "assets/onboard1.jpg",
      "title": "Identifikasi Cepat",
      "desc":
          "Pilih gejala tanaman Anda dan biarkan aplikasi mengidentifikasi penyakit yang mungkin ada."
    },
    {
      "image": "assets/onboard2.jpg",
      "title": "Panduan Lengkap",
      "desc":
          "Dapatkan informasi rinci tentang setiap penyakit, termasuk gejala dan cara penanganannya."
    },
    {
      "image": "assets/onboard3.jpg",
      "title": "Tips dan Trik",
      "desc":
          "Akses tips dan trik dari para ahli untuk menjaga tanaman cabai rawit Anda tetap sehat."
    },
  ];

  @override
  void initState() {
    super.initState();
    _controller = InfiniteScrollController(initialItem: 0);
    startAutoSlide();
  }

  void startAutoSlide() {
    _autoSlideTimer?.cancel(); // reset dulu
    _autoSlideTimer = Timer.periodic(const Duration(seconds: 3), (timer) {
      _controller.nextItem(
        duration: const Duration(milliseconds: 500),
        curve: Curves.easeInOut,
      );
    });
  }

  void pauseAutoSlide() {
    _autoSlideTimer?.cancel();
  }

  void resumeAutoSlideWithDelay() {
    _autoSlideTimer?.cancel();
    Future.delayed(const Duration(seconds: 5), () {
      if (mounted) {
        startAutoSlide();
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          NotificationListener<ScrollNotification>(
            onNotification: (notification) {
              if (notification is ScrollStartNotification) {
                pauseAutoSlide();
              } else if (notification is ScrollEndNotification) {
                resumeAutoSlideWithDelay();
              }
              return false;
            },
            child: InfiniteCarousel.builder(
              itemCount: onboardingData.length,
              itemExtent: MediaQuery.of(context).size.width,
              controller: _controller,
              onIndexChanged: (index) {
                setState(() {
                  currentIndex = index % onboardingData.length;
                });
              },
              itemBuilder: (context, index, realIndex) {
                final data = onboardingData[index % onboardingData.length];
                return Image.asset(
                  data['image']!,
                  fit: BoxFit.cover,
                  width: double.infinity,
                  height: double.infinity,
                );
              },
            ),
          ),
          Positioned(
            bottom: 200,
            left: 0,
            right: 0,
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: List.generate(
                    onboardingData.length,
                    (index) => buildDot(index),
                  ),
                ),
                const SizedBox(height: 20),
                Text(
                  onboardingData[currentIndex]['title']!,
                  style: const TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 8),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 40),
                  child: Text(
                    onboardingData[currentIndex]['desc']!,
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.white,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
              ],
            ),
          ),
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              padding: const EdgeInsets.all(20),
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(
                  top: Radius.circular(20),
                ),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Text(
                    "Masuk ke aplikasi RawitCare",
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  const Text(
                    "Dan mulai deteksi penyakit cabai rawit anda!!!",
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.black54,
                    ),
                  ),
                  const SizedBox(height: 16),
                  SizedBox(
                    width: double.infinity,
                    height: 45,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color.fromRGBO(172, 43, 54, 1),
                      ),
                      onPressed: () {
                        Navigator.pushReplacement(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const DiagnosisPage()));
                      },
                      child: const Text(
                        "Lanjutkan",
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                  const SizedBox(height: 8),
                  SizedBox(
                    width: double.infinity,
                    height: 45,
                    child: OutlinedButton(
                      onPressed: () {
                        SystemNavigator.pop();
                      },
                      style: OutlinedButton.styleFrom(
                        side: const BorderSide(color: Colors.black),
                      ),
                      child: const Text(
                        "Keluar",
                        style: TextStyle(color: Colors.black),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  AnimatedContainer buildDot(int index) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      margin: const EdgeInsets.symmetric(horizontal: 4),
      height: 8,
      width: currentIndex == index ? 20 : 8,
      decoration: BoxDecoration(
        color: currentIndex == index ? Colors.white : Colors.grey,
        borderRadius: BorderRadius.circular(4),
      ),
    );
  }
}
