import 'package:cargocalculaterapp/router/app_routes.dart';
import 'package:cargocalculaterapp/router/name_routes.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/model/price_calculate_request.dart';
import '../../domain/usecase/calculate_price_usecase.dart';
import '../arguments/calculator_info_argument.dart';

part 'calculator_event.dart';

part 'calculator_state.dart';

class CalculatorBloc extends Bloc<CalculatorEvent, CalculatorState> {
  CalculatorBloc(this.calculatePriceUseCase)
    : super(const CalculatorState(isLoading: false)) {
    on<WeightSizeEnterEvent>(_weightSizeEntered);
    on<WareHouseSelectEvent>(_wareHouseSelect);
    on<CalculateEvent>(_calculate);
  }

  final CalculatePriceUseCase calculatePriceUseCase;


  void _weightSizeEntered(
    WeightSizeEnterEvent event,
    Emitter<CalculatorState> emit,
  ) {
    emit(
      state.copyWith(
        size: double.tryParse(event.size.replaceAll(",", "")),
        weight: double.tryParse(event.weight.replaceAll(",", "")),
      ),
    );
  }

  void _wareHouseSelect(
    WareHouseSelectEvent event,
    Emitter<CalculatorState> emit,
  ) {
    emit(state.copyWith(selectedWarehouse: event.wareHouse));
  }

  Future<void> _calculate(
    CalculateEvent event,
    Emitter<CalculatorState> emit,
  ) async {
    emit(state.copyWith(isLoading: true));
    final response = await calculatePriceUseCase(
      PriceCalculateRequest(
        m3: state.size,
        avg: (state.weight ?? 0) / (state.size ?? 1),
      ),
    );
    response.fold(
      (l) {
        emit(state.copyWith(isLoading: false));
      },
      (r) {
        emit(state.copyWith(isLoading: false));
        Navigator.pushNamed(
          rootNavigatorKey.currentContext!,
          Routes.calculationInfo,
          arguments: CalculatorInfoArgument(
            productName: event.productName,
            deliveryPrice: r.price ?? 0,
            size: state.size ?? 0,
            averageWeight: (state.weight ?? 0) / (state.size ?? 1),
            weight: state.weight ?? 0,
            weraHouse: state.selectedWarehouse ?? "",
          ),
        );
      },
    );
  }
}
