import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/core/providers/app_provider.dart';
import 'package:niogu_app/features/supplier/data/repositories/supplier_repository_impl.dart';
import 'package:niogu_app/features/supplier/domain/entities/supplier.dart';
import 'package:niogu_app/features/supplier/domain/repositories/i_supplier_repository.dart';
import 'package:niogu_app/features/supplier/presentation/controllers/supplier_controller.dart';

final supplierRepositoryProvider = Provider.autoDispose<ISupplierRepository>((
  ref,
) {
  final appDatabase = ref.watch(appDatabaseProvider);

  return SupplierRepositoryImpl(appDatabase);
});

final supplierStreamProvider =
    StreamProvider.autoDispose<List<DisplaySuppliers>>((ref) {
      final supplierRepository = ref.watch(supplierRepositoryProvider);

      return supplierRepository.watchSuppliers();
    });

final supplierSearchProvider = StateProvider.autoDispose<String>((ref) => '');

final filteredSupplierProvider =
    Provider.autoDispose<AsyncValue<List<DisplaySuppliers>>>((ref) {
      final supplierStreamAsync = ref.watch(supplierStreamProvider);
      final supplierSearchAsync = ref.watch(supplierSearchProvider);
      return supplierStreamAsync.when(
        data: (suppliers) {
          if (supplierSearchAsync.trim().isEmpty) {
            return AsyncValue.data(suppliers);
          }

          final filteredSuppliers = suppliers.where((supplier) {
            return supplier.name.toLowerCase().contains(
              supplierSearchAsync.toLowerCase(),
            );
          }).toList();

          return AsyncValue.data(filteredSuppliers);
        },
        error: (error, stackTrace) {
          return AsyncValue.error(error, stackTrace);
        },
        loading: () => const AsyncValue.loading(),
      );
    });

final supplierEmptyProvider = Provider.autoDispose<SupplierEmpty>((ref) {
  final supplierStreamAsync = ref.watch(supplierStreamProvider);
  final filteredSupplierAsync = ref.watch(filteredSupplierProvider);
  final supplierSearchAsync = ref.watch(supplierSearchProvider);

  if (supplierStreamAsync.isLoading) {
    return SupplierEmpty.loading;
  }

  final allSuppliers = supplierStreamAsync.value ?? [];

  if (allSuppliers.isEmpty) {
    return SupplierEmpty.empty_database;
  }

  final filteredSuppliers = filteredSupplierAsync.value ?? [];

  if (supplierSearchAsync.isNotEmpty && filteredSuppliers.isEmpty) {
    return SupplierEmpty.empty_search_result;
  }

  return SupplierEmpty.has_data;
});

final supplierControllerProvider =
    AsyncNotifierProvider.autoDispose<SupplierController, void>(
      SupplierController.new,
    );
