import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../data/datasources/remote/trading_remote_datasource.dart';
import '../../data/models/c2c_order_model.dart';
import '../../core/di/injection.dart';

/// C2C市场订单列表 Provider
final c2cOrdersProvider = FutureProvider.family<C2cOrdersPageModel, String?>(
  (ref, type) async {
    final dataSource = getIt<TradingRemoteDataSource>();
    final result = await dataSource.getC2cOrders(type: type);

    ref.keepAlive();
    final timer = Timer(const Duration(seconds: 30), () {
      ref.invalidateSelf();
    });
    ref.onDispose(() => timer.cancel());

    return result;
  },
);

/// 我的C2C订单列表 Provider
final myC2cOrdersProvider = FutureProvider<C2cOrdersPageModel>(
  (ref) async {
    final dataSource = getIt<TradingRemoteDataSource>();
    final result = await dataSource.getMyC2cOrders();

    ref.keepAlive();
    final timer = Timer(const Duration(seconds: 30), () {
      ref.invalidateSelf();
    });
    ref.onDispose(() => timer.cancel());

    return result;
  },
);

/// C2C订单详情 Provider（autoDispose: 每次进入详情页都获取最新数据）
/// 活跃状态订单（PENDING/MATCHED/PAID）每10秒自动刷新，终态订单不刷新
final c2cOrderDetailProvider = FutureProvider.autoDispose.family<C2cOrderModel, String>(
  (ref, orderNo) async {
    final dataSource = getIt<TradingRemoteDataSource>();
    final result = await dataSource.getC2cOrderDetail(orderNo);

    // 活跃状态订单自动刷新（过期/完成/取消后停止刷新）
    if (result.isPending || result.isMatched || result.isPaid) {
      final timer = Timer(const Duration(seconds: 10), () {
        ref.invalidateSelf();
      });
      ref.onDispose(() => timer.cancel());
    }

    return result;
  },
);

/// C2C交易状态
class C2cTradingState {
  final bool isLoading;
  final String? error;
  final C2cOrderModel? lastOrder;

  C2cTradingState({
    this.isLoading = false,
    this.error,
    this.lastOrder,
  });

  C2cTradingState copyWith({
    bool? isLoading,
    String? error,
    C2cOrderModel? lastOrder,
    bool clearError = false,
  }) {
    return C2cTradingState(
      isLoading: isLoading ?? this.isLoading,
      error: clearError ? null : (error ?? this.error),
      lastOrder: lastOrder ?? this.lastOrder,
    );
  }
}

class C2cTradingNotifier extends StateNotifier<C2cTradingState> {
  final TradingRemoteDataSource _dataSource;

  C2cTradingNotifier(this._dataSource) : super(C2cTradingState());

  /// 创建C2C订单（发布广告）
  Future<bool> createOrder({
    required String type,
    required String price,
    required String quantity,
    String? minAmount,
    String? maxAmount,
    // 收款信息（卖单必填）
    String? paymentMethod,
    String? paymentAccount,
    String? paymentQrCode,
    String? paymentRealName,
    String? remark,
  }) async {
    state = state.copyWith(isLoading: true, clearError: true);
    try {
      final order = await _dataSource.createC2cOrder(
        type: type,
        price: price,
        quantity: quantity,
        minAmount: minAmount,
        maxAmount: maxAmount,
        paymentMethod: paymentMethod,
        paymentAccount: paymentAccount,
        paymentQrCode: paymentQrCode,
        paymentRealName: paymentRealName,
        remark: remark,
      );
      state = state.copyWith(isLoading: false, lastOrder: order);
      return true;
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
      return false;
    }
  }

  /// 接单
  Future<bool> takeOrder(
    String orderNo, {
    String? quantity,
    // 收款信息（接买单时由taker提供）
    String? paymentMethod,
    String? paymentAccount,
    String? paymentQrCode,
    String? paymentRealName,
  }) async {
    state = state.copyWith(isLoading: true, clearError: true);
    try {
      final order = await _dataSource.takeC2cOrder(
        orderNo,
        quantity: quantity,
        paymentMethod: paymentMethod,
        paymentAccount: paymentAccount,
        paymentQrCode: paymentQrCode,
        paymentRealName: paymentRealName,
      );
      state = state.copyWith(isLoading: false, lastOrder: order);
      return true;
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
      return false;
    }
  }

  /// 取消订单
  Future<bool> cancelOrder(String orderNo) async {
    state = state.copyWith(isLoading: true, clearError: true);
    try {
      await _dataSource.cancelC2cOrder(orderNo);
      state = state.copyWith(isLoading: false);
      return true;
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
      return false;
    }
  }

  /// 确认付款（买方操作）
  Future<bool> confirmPayment(String orderNo) async {
    state = state.copyWith(isLoading: true, clearError: true);
    try {
      final order = await _dataSource.confirmC2cPayment(orderNo);
      state = state.copyWith(isLoading: false, lastOrder: order);
      return true;
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
      return false;
    }
  }

  /// 确认收款（卖方操作）
  Future<bool> confirmReceived(String orderNo) async {
    state = state.copyWith(isLoading: true, clearError: true);
    try {
      final order = await _dataSource.confirmC2cReceived(orderNo);
      state = state.copyWith(isLoading: false, lastOrder: order);
      return true;
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
      return false;
    }
  }

  /// 上传付款水单（买方操作）
  Future<bool> uploadPaymentProof(String orderNo, String filePath) async {
    state = state.copyWith(isLoading: true, clearError: true);
    try {
      final order = await _dataSource.uploadC2cPaymentProof(orderNo, filePath);
      state = state.copyWith(isLoading: false, lastOrder: order);
      return true;
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
      return false;
    }
  }

  void clearError() {
    state = state.copyWith(clearError: true);
  }

  void clearState() {
    state = C2cTradingState();
  }
}

final c2cTradingNotifierProvider =
    StateNotifierProvider<C2cTradingNotifier, C2cTradingState>(
  (ref) => C2cTradingNotifier(getIt<TradingRemoteDataSource>()),
);
