import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/network/dio_client.dart';
import '../data/models/home/top_trader.dart';

/// 顶级交易员列表状态
class TopTraderState {
  final List<TopTrader> traders;
  final bool isLoading;

  const TopTraderState({
    this.traders = const [],
    this.isLoading = false,
  });

  TopTraderState copyWith({
    List<TopTrader>? traders,
    bool? isLoading,
  }) =>
      TopTraderState(
        traders: traders ?? this.traders,
        isLoading: isLoading ?? this.isLoading,
      );
}

class TopTraderNotifier extends Notifier<TopTraderState> {
  @override
  TopTraderState build() {
    Future.microtask(_fetch);
    return const TopTraderState(isLoading: true);
  }

  Future<void> refresh() => _fetch();

  Future<void> _fetch() async {
    try {
      final dio = ref.read(dioClientProvider);
      final resp = await dio.get<Map<String, dynamic>>(
        'follow/customer/top-trader-list',
        queryParameters: {'isTop': 1},
      );
      final data = resp.data?['data'];
      if (data == null) {
        state = state.copyWith(isLoading: false);
        return;
      }

      final records = (data['records'] as List<dynamic>?) ?? [];
      final traders = records
          .map((e) => TopTrader.fromJson(e as Map<String, dynamic>))
          .toList();

      state = TopTraderState(traders: traders, isLoading: false);
    } on DioException {
      state = state.copyWith(isLoading: false);
    }
  }
}

final topTraderProvider =
    NotifierProvider<TopTraderNotifier, TopTraderState>(TopTraderNotifier.new);
