import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../domain/provider/varient/varient_pro.dart';
import '../../domain/repository/varient/varient_repo.dart';
import '../../modules/product/product.dart';

class ProductVariantController extends GetxController {
  final ProductVariantRepository provider;

  ProductVariantController({required this.provider});

  // ──────────────────────────────────────────────────────────────────────
  // Reactive state
  // ──────────────────────────────────────────────────────────────────────
  final RxBool isLoading = false.obs;
  final RxList<Product> productVariants = <Product>[].obs;

  /// Selected variant ID (null = nothing selected)
  final RxnInt selectedProductId = RxnInt();

  /// Quantity per variant (default = 1)
  final RxMap<int, int> variantQuantities = <int, int>{}.obs;

  // ──────────────────────────────────────────────────────────────────────
  // Public helpers
  // ──────────────────────────────────────────────────────────────────────
  /// **Always call this before opening a new product’s variants**
  void clearVariantState() {
    productVariants.clear();
    selectedProductId.value = null;
    variantQuantities.clear();
    isLoading.value = false;
  }

  void selectVariant(int productId) {
    if (selectedProductId.value == productId) {
      selectedProductId.value = null; // allow deselection
    } else {
      selectedProductId.value = productId;
      // Initialise quantity = 1 if not present
      variantQuantities.putIfAbsent(productId, () => 1);
    }
  }

  void increaseQuantity(int productId) {
    final current = variantQuantities[productId] ?? 0;
    variantQuantities[productId] = current + 1;
  }

  void decreaseQuantity(int productId) {
    final current = variantQuantities[productId] ?? 0;
    if (current > 1) {
      variantQuantities[productId] = current - 1;
    }
  }

  // ──────────────────────────────────────────────────────────────────────
  // FETCH VARIANTS – **reset + safe init**
  // ──────────────────────────────────────────────────────────────────────
  Future<void> fetchVariants({
    required int tenantId,
    required int variantId,
  }) async {
    try {
      isLoading.value = true;

      // 1. ALWAYS start fresh
      clearVariantState();

      final variants = await provider.getProductVariant(
        tenantId: tenantId,
        variantId: variantId,
      );

      if (variants != null && variants.isNotEmpty) {
        productVariants.assignAll(variants);

        // 2. Initialise quantity = 1 for every variant
        for (final v in variants) {
          final pid = v.productid ?? 0;
          if (pid != 0) {
            variantQuantities[pid] = 1;
          }
        }

        // 3. Auto-select first variant
        final first = variants.first;
        if (first.productid != null) {
          selectedProductId.value = first.productid;
        }
      } else {
        productVariants.clear();
        variantQuantities.clear();
      }
    } catch (e, s) {
      debugPrint('fetchVariants error: $e\n$s');
      // Get.snackbar(
      //   'Error',
      //   'Failed to load variants',
      //   snackPosition: SnackPosition.TOP,
      //   backgroundColor: Colors.redAccent,
      //   colorText: Colors.white,
      // );
    } finally {
      isLoading.value = false;
    }
  }

  // ──────────────────────────────────────────────────────────────────────
  // Lifecycle
  // ──────────────────────────────────────────────────────────────────────
  @override
  void onClose() {
    clearVariantState();
    super.onClose();
  }
}