import 'dart:async';
import 'package:flutter/material.dart';
import 'package:top_news_app/helper/helper.dart';
import 'package:top_news_app/helper/image_cached.dart';

class CarouselMdOne extends StatefulWidget {
  final List<dynamic> images;

  const CarouselMdOne({super.key, required this.images});
  @override
  State<CarouselMdOne> createState() => _CarouselMdOneState();
}

class _CarouselMdOneState extends State<CarouselMdOne> {
  int _currentPage = 0;
  final _controller = PageController(
    initialPage: 0,
  );
  int totalLength = 0;

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

  getChangePage() async {
    try {
      Timer.periodic(const Duration(seconds: 3), (Timer timer) {
        if (_currentPage < totalLength) {
          _currentPage++;
        } else {
          _currentPage = 0;
        }

        if (_controller.hasClients) {
          _controller.animateToPage(
            _currentPage,
            duration: const Duration(milliseconds: 100),
            curve: Curves.easeInOut,
          );
        }
      });
    } catch (e) {
      rethrow;
    }
  }

  @override
  void initState() {
    super.initState();
    totalLength = widget.images.length;
    getChangePage();
  }

  Widget pageIndexIndicator(bool isCurrentPage) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 2.0),
      height: isCurrentPage ? 8.0 : 8.0,
      width: isCurrentPage ? 32.0 : 32.0,
      decoration: BoxDecoration(
        color: isCurrentPage ? primaryColors : Colors.grey,
        borderRadius: BorderRadius.circular(12),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Stack(
      children: [
        SizedBox(
          height: 250,
          child: PageView.builder(
              controller: _controller,
              onPageChanged: (int page) {
                setState(() {});
              },
              itemCount: totalLength,
              itemBuilder: (context, index) {
                return SizedBox(
                  height: 250,
                  width: size.width,
                  child: ImageCached(
                      image: widget.images[index],
                      width: size.width,
                      blur: false,
                      fit: BoxFit.cover,
                      height: 250),
                );
              }),
        ),
        Positioned(
            bottom: 6,
            left: 6,
            child: Container(
              padding: const EdgeInsets.all(4),
              child: Row(mainAxisSize: MainAxisSize.min, children: [
                for (int i = 0; i < totalLength; i++)
                  _currentPage == i
                      ? pageIndexIndicator(true)
                      : pageIndexIndicator(false)
              ]),
            ))
      ],
    );
  }
}
