import 'dart:developer';

import 'package:bloc/bloc.dart';
import 'package:enaklo_pos/data/datasources/product_local_datasource.dart';
import 'package:enaklo_pos/data/datasources/product_remote_datasource.dart';
import 'package:enaklo_pos/data/models/request/product_request_model.dart';
import 'package:enaklo_pos/data/models/response/product_response_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:image_picker/image_picker.dart';

part 'update_product_event.dart';
part 'update_product_state.dart';
part 'update_product_bloc.freezed.dart';

class UpdateProductBloc extends Bloc<UpdateProductEvent, UpdateProductState> {
  final ProductRemoteDatasource datasource;
  UpdateProductBloc(
    this.datasource,
  ) : super(const _Initial()) {
    on<_UpdateProduct>((event, emit) async {
      emit(const _Loading());
      
      try {
        // Validate required fields
        if (event.product.name == null || event.product.name!.isEmpty) {
          emit(_Error('Product name is required'));
          return;
        }
        
        if (event.product.price == null || event.product.price!.isEmpty) {
          emit(_Error('Product price is required'));
          return;
        }
        
        if (event.product.stock == null) {
          emit(_Error('Product stock is required'));
          return;
        }
        
        if (event.product.categoryId == null) {
          emit(_Error('Product category is required'));
          return;
        }
        
        // Parse price safely
        final price = int.tryParse(event.product.price!);
        if (price == null) {
          emit(_Error('Invalid price format'));
          return;
        }
        
        final requestData = ProductRequestModel(
          id: event.product.id,
          name: event.product.name!,
          price: price,
          stock: event.product.stock!,
          categoryId: event.product.categoryId!,
          isBestSeller: event.product.isFavorite ?? 0, // Default to 0 if null
          image: event.image,
          printerType: event.product.printerType ?? 'kitchen', // Default to kitchen if null
        );
        
        log("Update requestData: ${requestData.toString()}");
        log("Request map: ${requestData.toMap()}");
        
        final response = await datasource.updateProduct(requestData);
        response.fold(
          (l) => emit(_Error(l)),
          (r) async {
            // Update local database after successful API update
            try {
              await ProductLocalDatasource.instance.updateProduct(event.product);
              log("Local product updated successfully");
            } catch (e) {
              log("Error updating local product: $e");
            }
            emit(_Success('Update Product Success'));
          },
        );
      } catch (e) {
        log("Error in UpdateProductBloc: $e");
        emit(_Error('An error occurred: $e'));
      }
    });
  }
} 