import 'package:auto_route/annotations.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/features/earning/domain/bloc/earnings_bloc.dart';
import 'package:krow/features/earning/presentation/slivers/bottom_earnings_sliver.dart';
import 'package:krow/features/earning/presentation/slivers/earnings_header_sliver.dart';
import 'package:krow/features/earning/presentation/slivers/earnings_list_sliver.dart';

@RoutePage()
class EarningsScreen extends StatefulWidget {
  const EarningsScreen({super.key});

  @override
  State<EarningsScreen> createState() => _EarningsScreenState();
}

class _EarningsScreenState extends State<EarningsScreen> {
  final _scrollController = ScrollController();
  bool allowPagination = true;

  @override
  void initState() {
    super.initState();

    _scrollController.addListener(
      () {
        if (allowPagination &&
            _scrollController.position.userScrollDirection ==
                ScrollDirection.reverse &&
            _scrollController.position.extentAfter < 50) {
          context.read<EarningsBloc>().add(const LoadAdditionalEarnings());
          allowPagination = false;
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      body: RefreshIndicator(
        displacement: 80,
        backgroundColor: AppColors.bgColorLight,
        color: AppColors.bgColorDark,
        triggerMode: RefreshIndicatorTriggerMode.anywhere,
        onRefresh: () {
          context.read<EarningsBloc>().add(const ReloadCurrentEarnings());
          return Future.delayed(const Duration(seconds: 1));
        },
        child: BlocListener<EarningsBloc, EarningsState>(
          listenWhen: (previous, current) =>
              previous.currentTab.status != current.currentTab.status,
          listener: (context, state) {
            allowPagination = state.currentTab.status.allowLoad;
          },
          child: CustomScrollView(
            controller: _scrollController,
            physics: const ClampingScrollPhysics(),
            slivers: [
              const EarningsHeaderSliver(),
              const EarningsListSliver(),
              const BottomEarningsSliver(),
            ],
          ),
        ),
      ),
    );
  }

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