import 'package:autos/data/repositories/imports_repository_impl.dart';
import 'package:autos/domain/entities/import_product.dart';
import 'package:autos/presentation/providers/user_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';

/// ✅ Repository Provider
final importsRepositoryProvider = Provider<ImportsRepository>(
  (ref) => ImportsRepositoryImpl(ref.read(apiServiceProvider)),
);

/// ✅ Main Imports Provider
final importsProvider = StateNotifierProvider<
    ImportsNotifier, AsyncValue<List<ImportProductEntity>>>(
  (ref) => ImportsNotifier(ref.read(importsRepositoryProvider)),
);
class ImportsNotifier
    extends StateNotifier<AsyncValue<List<ImportProductEntity>>> {
  final ImportsRepository _repo;

  ImportsNotifier(this._repo) : super(const AsyncLoading());

  /// ✅ STATE
  int _page = 1;
  final int _pageSize = 48;

  String _category = "All";
  String _subcategory = "All";

  int get currentPage => _page;

  /// ✅ LOAD PRODUCTS FROM API
  Future<void> loadProducts({bool resetPage = false}) async {
    try {
      if (resetPage) _page = 1;

      state = const AsyncLoading();

      debugPrint("📡 Fetching products");
      debugPrint("➡ Page: $_page");
      debugPrint("➡ Category: $_category");
      debugPrint("➡ SubCategory: $_subcategory");

      final products = await _repo.getUserProducts(
        page: _page,
        pageSize: _pageSize,
        category: _category == "All" ? null : _category,
        subcategory: _subcategory == "All" ? null : _subcategory,
      );

      state = AsyncData(products);
    } catch (e, st) {
      state = AsyncError(e, st);
    }
  }

  /// ✅ CATEGORY CHANGE (RESETS SUBCATEGORY AUTOMATICALLY)
  void changeCategory(String value) {
    _category = value;
    _subcategory = "All"; // ✅ RESET HERE
    loadProducts(resetPage: true);
  }

  /// ✅ SUBCATEGORY CHANGE
  void changeSubcategory(String value) {
    _subcategory = value;
    loadProducts(resetPage: true);
  }

  /// ✅ NEXT PAGE
  void nextPage() {
    _page++;
    loadProducts();
  }

  /// ✅ PREVIOUS PAGE
  void prevPage() {
    if (_page > 1) {
      _page--;
      loadProducts();
    }
  }
}
