import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/network/dio_client.dart';
import '../data/models/finance/staking_team_overview.dart';
import '../data/services/staking_service.dart';

class StakingTeamState {
  final bool isLoading;
  final bool isLoadingMore;
  final String? errorMessage;
  final StakingTeamOverview? overview;
  final List<StakingDirectMember> directList;
  final int pageNo;
  final bool hasMore;

  const StakingTeamState({
    this.isLoading = false,
    this.isLoadingMore = false,
    this.errorMessage,
    this.overview,
    this.directList = const [],
    this.pageNo = 1,
    this.hasMore = false,
  });

  StakingTeamState copyWith({
    bool? isLoading,
    bool? isLoadingMore,
    String? errorMessage,
    StakingTeamOverview? overview,
    List<StakingDirectMember>? directList,
    int? pageNo,
    bool? hasMore,
  }) {
    return StakingTeamState(
      isLoading: isLoading ?? this.isLoading,
      isLoadingMore: isLoadingMore ?? this.isLoadingMore,
      errorMessage: errorMessage,
      overview: overview ?? this.overview,
      directList: directList ?? this.directList,
      pageNo: pageNo ?? this.pageNo,
      hasMore: hasMore ?? this.hasMore,
    );
  }
}

class StakingTeamNotifier extends AutoDisposeNotifier<StakingTeamState> {
  static const _pageSize = 20;

  StakingService get _service => StakingService(ref.read(dioClientProvider));

  @override
  StakingTeamState build() => const StakingTeamState();

  Future<void> init() async {
    state = state.copyWith(isLoading: true, errorMessage: null);
    try {
      final results = await Future.wait([
        _service.getTeamOverview(),
        _service.getDirectList(pageNo: 1, pageSize: _pageSize),
      ]);
      final overview = results[0] as StakingTeamOverview;
      final page = results[1] as StakingDirectListPage;
      state = state.copyWith(
        isLoading: false,
        overview: overview,
        directList: page.content,
        pageNo: page.pageNo,
        hasMore: page.hasMore,
      );
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        errorMessage: '$e',
        overview: null,
        directList: const [],
      );
    }
  }

  Future<void> loadMore() async {
    if (state.isLoadingMore || !state.hasMore) {
      return;
    }
    state = state.copyWith(isLoadingMore: true);
    try {
      final nextPage = state.pageNo + 1;
      final page = await _service.getDirectList(
        pageNo: nextPage,
        pageSize: _pageSize,
      );
      state = state.copyWith(
        isLoadingMore: false,
        directList: [...state.directList, ...page.content],
        pageNo: page.pageNo,
        hasMore: page.hasMore,
      );
    } catch (e) {
      state = state.copyWith(isLoadingMore: false, errorMessage: '$e');
    }
  }
}

final stakingTeamProvider =
    AutoDisposeNotifierProvider<StakingTeamNotifier, StakingTeamState>(
  StakingTeamNotifier.new,
);
