import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.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.hasClients) return;

      final maxScrollExtent = scrollController.position.maxScrollExtent;
      final current = scrollController.position.pixels;

      double next = current + 1;

      if (next >= maxScrollExtent) {

        next = 0;
      }

      scrollController.jumpTo(next);
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return NotificationListener<UserScrollNotification>(
      onNotification: (notification) {
        if (notification.direction != ScrollDirection.idle) {
          _onUserScroll(); // 用户滑动时暂停自动滚动
        }
        return false; // 不阻止子组件的事件传递
      },

      child: ListView.builder(
        padding: widget.padding,
        scrollDirection: widget.scrollDirection,
        itemCount: 1000000,
        itemBuilder: (context, index) {
          return widget.itemBuilder(context, index % widget.itemCount);
        },
        controller: scrollController,
      ),
    );
  }
}
