import 'dart:async';
import 'package:flutter/material.dart';
import 'package:top_news_app/helper/helper.dart';
import 'package:top_news_app/model/Article.dart';
import 'package:top_news_app/widget/newscard_widget_transparent_two.dart';

class CarouselWithIndicator extends StatefulWidget {
  final List<ArticleData> bannerData;
  const CarouselWithIndicator({super.key, required this.bannerData});
  @override
  State<StatefulWidget> createState() {
    return _CarouselWithIndicatorState();
  }
}

class _CarouselWithIndicatorState extends State<CarouselWithIndicator> {
  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.bannerData.length;
    getChangePage();
  }

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

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        SizedBox(
          height: 250,
          child: PageView.builder(
              controller: _controller,
              onPageChanged: (int page) {
                setState(() {});
              },
              itemCount: totalLength,
              itemBuilder: (context, index) {
                return NewsCardWidgetTransparentTwo(
                    post: widget.bannerData[index]);
              }),
        ),
        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)
              ]),
            ))
      ],
    );
  }
}
