import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/core/enums/item_type.dart';
import 'package:niogu_app/features/stock_in/domain/entities/stock_in.dart';
import 'package:niogu_app/features/stock_in/domain/repositories/i_stock_in_repository.dart';
import 'package:niogu_app/features/stock_in/presentation/provider/stock_in_provider.dart';

class StockInController extends AutoDisposeAsyncNotifier<void> {
  late final IStockInRepository _stockInRepository;

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

  Future<void> updateStockItem({
    SupplierInformation? supplierInfo,
    NewPurchase? newPurchase,
    List<ItemPurchase>? itemPurchases,
    required List<UpdateStockItem> items,
  }) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _stockInRepository.updateStockItem(
        supplierInfo,
        newPurchase,
        itemPurchases,
        items,
      );
    });

    state = result;

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

class SelectedItemController extends StateNotifier<Map<String, SelectedItem>> {
  final SelectedItemType _type;

  SelectedItemController(this._type) : super({});

  void increment(String id) {
    final item = state[id];

    if (item == null) return;

    state = {...state, item.id: item.copyWith(quantity: item.quantity + 1)};
  }

  void decrement(String id) {
    final item = state[id];

    if (item == null) return;

    state = {...state, item.id: item.copyWith(quantity: item.quantity - 1)};
  }

  void toggleSelectAll(SelectedItem item) {
    if (state.containsKey(item.id)) {
      state = {...state}
        ..remove(item.id)
        ..[item.id] = item;
    } else {
      state = {...state, item.id: item};
    }
  }

  void toggle(SelectedItem item) {
    if (state.containsKey(item.id)) {
      state = {...state}..remove(item.id);
    } else {
      state = {...state, item.id: item};
    }
  }

  void customQuantity(String id, double quantity) {
    final item = state[id];

    if (item == null) return;

    state = {...state, id: item.copyWith(quantity: quantity)};
  }

  void delete(String id) {
    final item = state[id];

    if (item == null) return;

    state = {...state}..remove(id);
  }

  void clear(ItemType itemType) {
    state = {...state}
      ..removeWhere((_, value) {
        return value.itemType == itemType && value.type == _type;
      });
  }

  void restore(Map<String, SelectedItem> initialItems) {
    state = Map.from(initialItems);
  }
}
