import 'dart:async';

import 'package:flutter/cupertino.dart';

class AutoScrollListView extends StatefulWidget {
  final NullableIndexedWidgetBuilder itemBuilder;

  final int itemCount;

  final Axis scrollDirection;

  final EdgeInsetsGeometry? padding;

  final bool isAutoScrolling;

  const AutoScrollListView({
    super.key,
    required this.itemBuilder,
    required this.itemCount,
    this.padding,
    this.isAutoScrolling = true,
    this.scrollDirection = Axis.horizontal,
  });

  @override
  State<AutoScrollListView> createState() => _AutoScrollListViewState();
}

class _AutoScrollListViewState extends State<AutoScrollListView> {
  final ScrollController scrollController = ScrollController();
  Timer? _timer;
  bool _isUserScrolling = true;

  @override
  void initState() {
    super.initState();
    _isUserScrolling = widget.isAutoScrolling;
    _startAutoScroll();
  }

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

  void _startAutoScroll() {
    _timer = Timer.periodic(Duration(milliseconds: 50), (timer) {
      if (_isUserScrolling) {
        scrollController.animateTo(
          scrollController.position.pixels + 1,
          duration: Duration(milliseconds: 50),
          curve: Curves.linear,
        );
      }
    });
  }

  void _onUserScroll() {
    if (!_isUserScrolling) {
      return;
    }
    _timer?.cancel();
    _timer = Timer(Duration(seconds: 1), () {
      setState(() {
        _isUserScrolling = widget.isAutoScrolling;
      });
      _startAutoScroll();
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanDown: (_) => _onUserScroll(),
      onPanUpdate: (_) => _onUserScroll(),
      child: ListView.builder(
        padding: widget.padding,
        scrollDirection: widget.scrollDirection,
        itemCount: 1000000,
        itemBuilder: (context, index) {
          return widget.itemBuilder(context, index % widget.itemCount);
        },
        controller: scrollController,
      ),
    );
  }
}
