import 'dart:developer';

import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

import 'package:enaklo_pos/core/extensions/string_ext.dart';
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/product_local_datasource.dart';

import '../../models/order_model.dart';
import '../../models/product_quantity.dart';
import '../../models/order_type.dart';

part 'order_bloc.freezed.dart';
part 'order_event.dart';
part 'order_state.dart';

class OrderBloc extends Bloc<OrderEvent, OrderState> {
  final OrderRemoteDatasource orderRemoteDatasource;
  OrderBloc(
    this.orderRemoteDatasource,
  ) : super(const _Initial()) {
    log("🔧 OrderBloc: Constructor called");
    log("🔧 OrderBloc: OrderRemoteDatasource instance: $orderRemoteDatasource");
    on<_Order>((event, emit) async {
      log("🎯 OrderBloc: Event handler triggered!");
      emit(const _Loading());
      log("🚀 OrderBloc: Starting order process");
      log("📋 Order event received: ${event.toString()}");
      log("Start 1");

      final subTotal = event.items.fold<int>(
          0,
          (previousValue, element) =>
              previousValue +
              (element.product.price!.toIntegerFromText * element.quantity));
      // final total = subTotal + event.tax + event.serviceCharge - event.discount;

      final totalItem = event.items.fold<int>(
          0, (previousValue, element) => previousValue + element.quantity);

      final userData = await AuthLocalDataSource().getAuthData();

      final dataInput = OrderModel(
        subTotal: subTotal,
        paymentAmount: event.paymentAmount,
        tax: event.tax,
        discount: event.discount,
        discountAmount: event.discountAmount,
        serviceCharge: event.serviceCharge,
        total: event.totalPriceFinal,
        paymentMethod: event.paymentMethod,
        totalItem: totalItem,
        idKasir: userData.user?.id ?? 1,
        namaKasir: userData.user?.name ?? 'Kasir A',
        transactionTime: DateTime.now().toIso8601String(),
        customerName: event.customerName,
        tableNumber: event.tableNumber,
        status: event.status,
        paymentStatus: event.paymentStatus,
        isSync: 0,
        orderItems: event.items,
        orderType: event.orderType,
      );
      log("Start 2");

      //check state online or offline
      
      log("🔄 About to call API to save order...");
      log("📤 Order data being sent to API: ${dataInput.toServerMap()}");
      log("🌐 OrderRemoteDatasource instance: $orderRemoteDatasource");
      
      bool value = false;
      try {
        value = await orderRemoteDatasource.saveOrder(dataInput);
        log("📥 API response received: $value");
      } catch (e) {
        log("💥 Error calling API: $e");
        value = false;
      }
      int id = 0;
      if (value) {
        id = await ProductLocalDatasource.instance
            .saveOrder(dataInput.copyWith(isSync: 1));
      } else {
        id = await ProductLocalDatasource.instance
            .saveOrder(dataInput.copyWith(isSync: 1));
      }

      emit(_Loaded(
        dataInput,
        id,
      ));
    });
  }
}
