import 'dart:developer';

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

import '../../../common/types/split_type.dart';
import '../../../domain/order/order.dart';
import '../../../domain/payment_method/payment_method.dart';

part 'payment_form_event.dart';
part 'payment_form_state.dart';
part 'payment_form_bloc.freezed.dart';

@injectable
class PaymentFormBloc extends Bloc<PaymentFormEvent, PaymentFormState> {
  final IOrderRepository _repository;
  PaymentFormBloc(this._repository) : super(PaymentFormState.initial()) {
    on<PaymentFormEvent>(_onPaymentFormEvent);
  }

  Future<void> _onPaymentFormEvent(
    PaymentFormEvent event,
    Emitter<PaymentFormState> 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));
      },
      setPaymentMethod: (e) async {
        emit(state.copyWith(paymentMethod: e.paymentMethod));
      },
      submitted: (e) async {
        Either<OrderFailure, Payment> failureOrPayment;

        // Generate new idempotency key saat user intent (tap Bayar)
        // Kalau sedang retry (isSubmitting sebelumnya gagal), pakai key yang sama
        final idempotencyKey = state.idempotencyKey ?? const Uuid().v4();

        emit(state.copyWith(
          isSubmitting: true,
          failureOrPayment: none(),
          idempotencyKey: idempotencyKey,
        ));

        final request = PaymentRequest(
          orderId: state.order.id,
          paymentMethodId: state.paymentMethod?.id ?? '',
          amount: state.order.totalAmount,
          transactionId: '',
          splitNumber: 1,
          splitTotal: 1,
          splitDescription: '',
          paymentOrderItems: state.pendingItems
              .map(
                (item) => PaymentItemRequest(
                  orderItemId: item.id,
                  amount: item.totalPrice,
                ),
              )
              .toList(),
        );

        failureOrPayment = await _repository.createPayment(
          request: request,
          idempotencyKey: idempotencyKey,
        );

        emit(
          state.copyWith(
            isSubmitting: false,
            failureOrPayment: optionOf(failureOrPayment),
            // Clear key on success, keep on failure for retry
            idempotencyKey: failureOrPayment.isRight() ? null : idempotencyKey,
          ),
        );
      },
      submittedSplitBill: (e) async {
        Either<OrderFailure, Payment> failureOrPayment;

        // Generate new idempotency key untuk split bill
        final idempotencyKey = state.splitBillIdempotencyKey ?? const Uuid().v4();

        emit(
          state.copyWith(
            isSubmitting: true,
            failureOrPaymentSplitBill: none(),
            splitBillIdempotencyKey: idempotencyKey,
          ),
        );

        final request = PaymentSplitBillRequest(
          orderId: state.order.id,
          paymentMethodId: state.paymentMethod?.id ?? '',
          amount: state.order.totalAmount,
          customerId: e.customerId ?? '',
          type: e.splitType ?? SplitType.unknown,
          customerName: e.customerName ?? '',
          items: state.pendingItems
              .map(
                (item) => PaymentItemSplitBillRequest(
                  orderItemId: item.id,
                  quantity: item.quantity,
                ),
              )
              .toList(),
        );

        log(request.toString());

        failureOrPayment = await _repository.createSplitBill(
          request,
          idempotencyKey: idempotencyKey,
        );

        emit(
          state.copyWith(
            isSubmitting: false,
            failureOrPaymentSplitBill: optionOf(failureOrPayment),
            // Clear key on success, keep on failure for retry
            splitBillIdempotencyKey:
                failureOrPayment.isRight() ? null : idempotencyKey,
          ),
        );
      },
    );
  }
}
