import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../domain/entities/trade_order.dart';
import '../../domain/usecases/trading/buy_shares.dart';
import '../../domain/usecases/trading/sell_shares.dart';
import '../../core/di/injection.dart';

// Use Cases Providers
final buySharesUseCaseProvider = Provider<BuyShares>((ref) {
  return getIt<BuyShares>();
});

final sellSharesUseCaseProvider = Provider<SellShares>((ref) {
  return getIt<SellShares>();
});

// K线周期选择
final selectedKlinePeriodProvider = StateProvider<String>((ref) => '1h');

// 交易状态
class TradingState {
  final bool isLoading;
  final String? error;
  final TradeOrder? lastOrder;

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

  TradingState copyWith({
    bool? isLoading,
    String? error,
    TradeOrder? lastOrder,
  }) {
    return TradingState(
      isLoading: isLoading ?? this.isLoading,
      error: error,
      lastOrder: lastOrder ?? this.lastOrder,
    );
  }
}

class TradingNotifier extends StateNotifier<TradingState> {
  final BuyShares buySharesUseCase;
  final SellShares sellSharesUseCase;

  TradingNotifier({
    required this.buySharesUseCase,
    required this.sellSharesUseCase,
  }) : super(TradingState());

  Future<bool> buyShares(String accountSequence, String amount) async {
    state = state.copyWith(isLoading: true, error: null);

    final result = await buySharesUseCase(
      BuySharesParams(accountSequence: accountSequence, amount: amount),
    );

    return result.fold(
      (failure) {
        state = state.copyWith(isLoading: false, error: failure.message);
        return false;
      },
      (order) {
        state = state.copyWith(isLoading: false, lastOrder: order);
        return true;
      },
    );
  }

  Future<bool> sellShares(String accountSequence, String amount) async {
    state = state.copyWith(isLoading: true, error: null);

    final result = await sellSharesUseCase(
      SellSharesParams(accountSequence: accountSequence, amount: amount),
    );

    return result.fold(
      (failure) {
        state = state.copyWith(isLoading: false, error: failure.message);
        return false;
      },
      (order) {
        state = state.copyWith(isLoading: false, lastOrder: order);
        return true;
      },
    );
  }

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

final tradingNotifierProvider = StateNotifierProvider<TradingNotifier, TradingState>(
  (ref) => TradingNotifier(
    buySharesUseCase: ref.watch(buySharesUseCaseProvider),
    sellSharesUseCase: ref.watch(sellSharesUseCaseProvider),
  ),
);
