import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_ecommerce_v1/core/models/tenant_model.dart';
import 'package:niogu_ecommerce_v1/core/providers/app_provider.dart';
import 'package:niogu_ecommerce_v1/features/home/data/datasource/home_remote_datasource_impl.dart';
import 'package:niogu_ecommerce_v1/features/home/data/repositories/home_repository_impl.dart';
import 'package:niogu_ecommerce_v1/features/home/domain/entities/home.dart';
import 'package:niogu_ecommerce_v1/features/home/domain/repositories/i_home_repository.dart';
import 'package:niogu_ecommerce_v1/features/home/presentation/controllers/home_controller.dart';

final homeRemoteDataSourceProvider =
    Provider.autoDispose<IHomeRemoteDatasource>((ref) {
      final dio = ref.watch(dioProvider);
      return HomeRemoteDatasourceImpl(dio);
    });

final homeRepositoryProvider = Provider.autoDispose<IHomeRepository>((ref) {
  final homeRemoteDataSource = ref.watch(homeRemoteDataSourceProvider);

  return HomeRepositoryImpl(homeRemoteDataSource);
});

final configurationControllerProvider =
    AsyncNotifierProvider.autoDispose<ConfigurationController, TenantModel?>(
      ConfigurationController.new,
    );

final homeControllerProvider =
    AsyncNotifierProvider.autoDispose<HomeController, Home?>(
      HomeController.new,
    );

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

final productByNameControllerProvider = AsyncNotifierProvider.family
    .autoDispose<ProductByNameController, List<ProductItem>, String>(
      ProductByNameController.new,
    );

final productByNameProvider =
    Provider.autoDispose<AsyncValue<List<ProductItem>>>((ref) {
      final productSearch = ref.watch(productSearchProvider);

      if (productSearch.isEmpty) {
        return AsyncValue.data([]);
      }

      return ref.watch(productByNameControllerProvider(productSearch));
    });

final processSearchStateProvider = StateProvider.autoDispose<ProcessSearch?>(
  (ref) => null,
);

final processSearchProvider = Provider.autoDispose<ProcessSearch>((ref) {
  final productSearchAsync = ref.watch(productSearchProvider);

  if (productSearchAsync.isEmpty) {
    return ProcessSearch.initial;
  }

  final processSearchState = ref.watch(processSearchStateProvider);

  if (processSearchState != null) {
    return processSearchState;
  }

  return ProcessSearch.suggestion;
});

final productCategoriesControllerProvider = AsyncNotifierProvider.family
    .autoDispose<ProductCategoryController, List<ProductItem>, String>(
      ProductCategoryController.new,
    );
