import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class AppRefreshList<T> extends StatefulWidget {
  const AppRefreshList({
    super.key,
    required this.items,
    required this.itemBuilder,
    this.onRefresh,
    this.onLoadMore,
    this.enablePullUp = false,
    this.separator,
    this.empty,
    this.padding,
  });

  final List<T> items;
  final Widget Function(BuildContext context, T item, int index) itemBuilder;
  final Future<void> Function()? onRefresh;
  final Future<void> Function()? onLoadMore;
  final bool enablePullUp;
  final Widget? separator;
  final Widget? empty;
  final EdgeInsetsGeometry? padding;

  @override
  State<AppRefreshList<T>> createState() => _AppRefreshListState<T>();
}

class _AppRefreshListState<T> extends State<AppRefreshList<T>> {
  final _controller = RefreshController();

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

  Future<void> _refresh() async {
    try {
      await widget.onRefresh?.call();
      _controller.refreshCompleted();
    } catch (_) {
      _controller.refreshFailed();
    }
  }

  Future<void> _loadMore() async {
    try {
      await widget.onLoadMore?.call();
      _controller.loadComplete();
    } catch (_) {
      _controller.loadFailed();
    }
  }

  @override
  Widget build(BuildContext context) {
    final child = widget.items.isEmpty && widget.empty != null
        ? widget.empty!
        : ListView.separated(
            padding: widget.padding,
            itemCount: widget.items.length,
            separatorBuilder: (_, _) =>
                widget.separator ?? SizedBox(height: 8.h),
            itemBuilder: (context, index) {
              return widget.itemBuilder(context, widget.items[index], index);
            },
          );

    return SmartRefresher(
      controller: _controller,
      enablePullDown: widget.onRefresh != null,
      enablePullUp: widget.enablePullUp && widget.onLoadMore != null,
      onRefresh: _refresh,
      onLoading: _loadMore,
      child: child,
    );
  }
}
