import 'dart:developer';

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

import '../../../common/types/order_type.dart';
import '../../../domain/delivery/delivery.dart';
import '../../../domain/order/order.dart';
import '../../../domain/product/product.dart';
import '../../../domain/table/table.dart';

part 'checkout_form_event.dart';
part 'checkout_form_state.dart';
part 'checkout_form_bloc.freezed.dart';

@injectable
class CheckoutFormBloc extends Bloc<CheckoutFormEvent, CheckoutFormState> {
  CheckoutFormBloc() : super(CheckoutFormState.initial()) {
    on<CheckoutFormEvent>(_onCheckoutFormEvent);
  }
  Future<void> _onCheckoutFormEvent(
    CheckoutFormEvent event,
    Emitter<CheckoutFormState> emit,
  ) {
    return event.map(
      addItem: (e) async {
        final currentState = state;
        emit(currentState.copyWith(isLoading: true));

        List<ProductQuantity> items = [...currentState.items];

        final index = items.indexWhere(
          (element) =>
              element.product.id == e.product.id &&
              element.variant?.id == e.variant?.id,
        );

        if (index != -1) {
          // Jika sudah ada → tambah quantity
          items[index] = items[index].copyWith(
            quantity: items[index].quantity + 1,
          );
        } else {
          // Jika belum ada → tambahkan item baru
          items.add(
            ProductQuantity(
              product: e.product,
              quantity: 1,
              variant: e.variant,
              notes: '',
            ),
          );
        }

        log('🛒 Items updated: ${items.length} items total ${items.toList()}');

        final totalQuantity = items.fold<int>(
          0,
          (sum, item) => sum + item.quantity,
        );

        final totalPrice = state.items.isEmpty
            ? 0.0
            : state.items
                  .map(
                    (e) =>
                        (e.product.price * e.quantity) +
                        (e.variant?.priceModifier ?? 0),
                  )
                  .reduce((value, element) => value + element);

        emit(
          currentState.copyWith(
            items: items,
            totalQuantity: totalQuantity,
            totalPrice: totalPrice.toInt(),
            isLoading: false,
          ),
        );
      },
      removeItem: (e) async {
        final currentState = state;
        emit(currentState.copyWith(isLoading: true));
        List<ProductQuantity> items = [...currentState.items];

        final index = items.indexWhere(
          (element) =>
              element.product.id == e.product.id &&
              element.variant?.id == e.variant?.id,
        );

        if (index != -1) {
          final currentItem = items[index];
          if (currentItem.quantity > 1) {
            // Kurangi quantity
            items[index] = currentItem.copyWith(
              quantity: currentItem.quantity - 1,
            );
          } else {
            // Hapus item kalau quantity = 1
            items.removeAt(index);
          }
        }

        final totalQuantity = items.fold<int>(
          0,
          (sum, item) => sum + item.quantity,
        );
        final totalPrice = items.fold<int>(
          0,
          (sum, item) =>
              sum +
              (item.quantity *
                  (item.variant?.priceModifier.toInt() ??
                      item.product.price.toInt())),
        );

        log(
          '🗑️ Item removed. Total items: ${items.length}, totalQuantity: $totalQuantity, totalPrice: $totalPrice',
        );

        // Emit state baru
        emit(
          currentState.copyWith(
            items: items,
            totalQuantity: totalQuantity,
            totalPrice: totalPrice,
            isLoading: false,
          ),
        );
      },
      started: (e) async {
        emit(CheckoutFormState.initial().copyWith(isLoading: true));
        try {
          emit(
            CheckoutFormState.initial().copyWith(
              items: e.items,
              tax: 0,
              serviceCharge: 0,
              isLoading: false,
            ),
          );
        } catch (e) {
          // Kalau gagal, pakai default values
          log('⚠️ Failed to load settings: $e');
          emit(
            CheckoutFormState.initial().copyWith(
              tax: 10,
              serviceCharge: 5,
              isLoading: false,
            ),
          );
        }
      },
      updateItemNotes: (e) async {
        final currentState = state;

        // Clone list items agar tidak mutasi langsung
        final items = [...currentState.items];
        final index = items.indexWhere(
          (element) => element.product.id == e.product.id,
        );

        if (index != -1) {
          items[index] = items[index].copyWith(notes: e.notes);
        }

        emit(currentState.copyWith(items: items, isLoading: false));
      },
      updateOrderType: (e) async {
        emit(state.copyWith(orderType: e.orderType));
      },
      updateDelivery: (e) async {
        emit(state.copyWith(delivery: e.delivery));
      },
      updateTable: (e) async {
        emit(state.copyWith(table: e.table));
      },
      orderAddedItems: (e) async {
        emit(state.copyWith(orderAdded: e.order));
      },
      customerNameChanged: (e) async {
        emit(state.copyWith(customerName: e.name,));
      }
    );
  }
}
