import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/core/system/system_setting.dart';
import 'package:niogu_app/features/pos/domain/entities/pos.dart';
import 'package:niogu_app/features/pos/domain/repositories/i_pos_repository.dart';
import 'package:niogu_app/features/pos/presentation/providers/pos_provider.dart';

class PosController extends AutoDisposeAsyncNotifier<void> {
  late final IPosRepository _posRepository;

  @override
  FutureOr<void> build() {
    _posRepository = ref.read(posRepositoryProvider);
  }

  Future<void> addSale(
    CustomerInformation? customer,
    NewSale newSale,
    List<ItemSale> itemSales,
  ) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _posRepository.addSale(customer, newSale, itemSales);
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }
}

class CartItemsController extends StateNotifier<Map<String, CartItems>> {
  CartItemsController() : super({});

  bool isInCart(String productVariantId) => state.containsKey(productVariantId);

  double quantityOf(String productVariantId) =>
      state[productVariantId]?.quantity ?? 0.0;

  Future<void> increment(DisplayProductPos product) async {
    final cartItem = state[product.productVariantId];

    if (cartItem == null) {
      final currentOutletId = await SystemSetting.getCurrentOutletId();

      state = {
        ...state,
        product.productVariantId: CartItems(
          currentOutletId: currentOutletId!,
          outletInventoryId: product.outletInventoryId,
          id: product.productVariantId,
          imagePath: product.imagePath,
          name: product.name,
          variantName: product.hasVariant ? product.variantName : null,
          currentSold: product.currentSold,
          quantity: 1,
          costPrice: product.costPrice,
          sellingPrice: product.sellingPrice,
          stockType: product.stockType,
          remainingStock: product.remainingStock,
          unit: product.unitName,
        ),
      };
    } else {
      state = {
        ...state,
        product.productVariantId: cartItem.copyWith(
          quantity: cartItem.quantity + 1,
        ),
      };
    }
  }

  void decrement(String productVariantId) {
    final cartItem = state[productVariantId];

    if (cartItem == null) return;

    if (cartItem.quantity <= 1) {
      state = {...state}..remove(productVariantId);
    } else {
      state = {
        ...state,
        productVariantId: cartItem.copyWith(quantity: cartItem.quantity - 1),
      };
    }
  }

  void customQuantity(String productVariantId, double quantity) {
    final cartItem = state[productVariantId];

    if (cartItem == null) return;

    state = {...state, productVariantId: cartItem.copyWith(quantity: quantity)};
  }

  void delete(String productVariantId) =>
      state = {...state}..remove(productVariantId);
}
