import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/network/dio_client.dart';
import '../data/models/market/funding_rate.dart';
import '../data/services/funding_rate_service.dart';

// ── State ─────────────────────────────────────────────────

class FundingRateState {
  final bool isLoading;
  final FundingRateCurrent? current;
  final List<FundingRateHistoryItem> history;
  final String? error;

  const FundingRateState({
    this.isLoading = false,
    this.current,
    this.history = const [],
    this.error,
  });

  FundingRateState copyWith({
    bool? isLoading,
    FundingRateCurrent? current,
    List<FundingRateHistoryItem>? history,
    String? error,
  }) {
    return FundingRateState(
      isLoading: isLoading ?? this.isLoading,
      current: current ?? this.current,
      history: history ?? this.history,
      error: error,
    );
  }
}

// ── Notifier ──────────────────────────────────────────────

class FundingRateNotifier extends FamilyNotifier<FundingRateState, int> {
  late FundingRateService _service;

  @override
  FundingRateState build(int contractCoinId) {
    _service = FundingRateService(ref.read(dioClientProvider));
    Future.microtask(() => load());
    return const FundingRateState(isLoading: true);
  }

  Future<void> load() async {
    if (!state.isLoading) {
      state = state.copyWith(isLoading: true);
    }
    try {
      final results = await Future.wait([
        _service.getCurrent(arg),
        // 多页拉取，service 内部保证覆盖最近 7 天
        _service.getHistory(contractCoinId: arg, days: 7),
      ]);

      final current = results[0] as FundingRateCurrent?;
      final rawHistory = results[1] as List<FundingRateHistoryItem>;

      // 二次过滤（防止跨页边界多出的旧数据），按时间升序排列
      final cutoff = DateTime.now().subtract(const Duration(days: 7));
      final sorted = rawHistory
          .where((e) => e.fundingTime.isAfter(cutoff))
          .toList()
        ..sort((a, b) => a.fundingTime.compareTo(b.fundingTime));

      state = FundingRateState(
        isLoading: false,
        current: current,
        history: sorted,
      );
    } catch (e) {
      debugPrint('[FundingRate] load error: $e');
      state = state.copyWith(isLoading: false, error: e.toString());
    }
  }
}

final fundingRateProvider =
    NotifierProviderFamily<FundingRateNotifier, FundingRateState, int>(
  FundingRateNotifier.new,
);
