import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart' hide Order;

import '../../../common/extension/extension.dart';
import '../../../common/types/split_type.dart';
import '../../../domain/customer/customer.dart';
import '../../../domain/order/order.dart';

part 'split_bill_form_event.dart';
part 'split_bill_form_state.dart';
part 'split_bill_form_bloc.freezed.dart';

@injectable
class SplitBillFormBloc extends Bloc<SplitBillFormEvent, SplitBillFormState> {
  SplitBillFormBloc() : super(SplitBillFormState.initial()) {
    on<SplitBillFormEvent>(_onSplitBillFormEvent);
  }

  Future<void> _onSplitBillFormEvent(
    SplitBillFormEvent event,
    Emitter<SplitBillFormState> emit,
  ) {
    return event.map(
      setOrder: (e) async {
        List<OrderItem> pendingItems = e.order.orderItems
            .where((item) => item.status == 'pending')
            .toList();

        emit(
          state.copyWith(
            order: e.order,
            pendingItems: pendingItems,
            splitType: e.order.splitType.isEmpty
                ? SplitType.amount
                : e.order.splitType.toSplitType(),
          ),
        );
      },
      customerChanged: (e) async {
        emit(state.copyWith(customer: e.customer));
      },
      customerNameChanged: (e) async {
        emit(state.copyWith(customerName: e.customerName));
      },
      splitTypeChanged: (e) async {
        emit(
          state.copyWith(
            splitType: e.splitType,
            totalAmount: 0,
            selectedProducts: {},
          ),
        );
      },
      itemQuantityChanged: (e) async {
        final newQuantities = Map<String, int>.from(state.selectedProducts);

        if (e.quantity > 0) {
          newQuantities[e.itemId] = e.quantity;
        } else {
          newQuantities.remove(e.itemId);
        }

        // Recalculate total price
        int newTotal = 0;
        for (var entry in newQuantities.entries) {
          final item = state.pendingItems.firstWhere(
            (item) => item.id == entry.key,
          );
          newTotal += item.unitPrice.toInt() * entry.value;
        }

        emit(
          state.copyWith(
            selectedProducts: newQuantities,
            totalAmount: newTotal,
          ),
        );
      },
      amountChanged: (e) async {
        emit(state.copyWith(totalAmount: e.amount));
      },
    );
  }
}
