import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../Data/Repository/products_repo/get_products.dart';
import '../../Helper/Logger.dart';
import '../../Model/Request/products/update_product.dart';
import '../../Model/Response/Orders/Getorderresponse.dart';
import '../../Model/Response/products/product_info.dart';
import '../../Model/Response/products/product_response.dart';
import '../../Model/Response/products/product_update_response.dart';

class ProductController extends GetxController {
  final ProductsRepository productsRepository = ProductsRepository();

  /// Main list used by UI
  RxList<ProductData> product = <ProductData>[].obs;

  /// Backup full list for search restore
  RxList<ProductData> masterProductList = <ProductData>[].obs;

  RxBool isProductLoading = true.obs;
  RxSet<int> loadingIndices = <int>{}.obs;
  RxBool isSearchModeEnable = false.obs;

  var productDetail = <ProductDetails>[].obs;

  TextEditingController productSearchController = TextEditingController();

  @override
  void onClose() {
    productSearchController.dispose();
    super.onClose();
  }

  // ---------------------------------------------------------
  // Toggle Availability
  // ---------------------------------------------------------
  Future<void> toggleAvailability(int index) async {
    loadingIndices.add(index);
    update();

    final oldProduct = product[index];
    final newStatus = oldProduct.status == 'Active' ? 'outofstock' : 'Active';

    // Optimistic local update
    product[index] = oldProduct.copyWith(status: newStatus);
    update();

    try {
      await updateProduct(oldProduct.productlocationid ?? 0, newStatus);
    } catch (e) {
      // API failed → revert UI
      product[index] = oldProduct;
      update();
      Get.snackbar('Error', 'Failed to update status');
    } finally {
      loadingIndices.remove(index);
      update();
    }
  }

  bool hasLoadedOnce = false;

  // ---------------------------------------------------------
  // Fetch Products (API)
  // ---------------------------------------------------------
  Future<void> getProducts({String? keyword}) async {
    if (keyword == null || keyword.isEmpty) {
      isSearchModeEnable.value = false;
    } else {
      isSearchModeEnable.value = true;
    }

    if (!isSearchModeEnable.value && !hasLoadedOnce) {
      isProductLoading.value = true;
      update();
    }

    try {
      final result = await productsRepository.getProducts(
        subCategoryId: 0,
        keyword: keyword,
      );

      // Store full list
      masterProductList.assignAll(result?.details ?? []);

      // Show full list
      product.assignAll(masterProductList);

      logger.i('Products Loaded : ${product.length}');
    } catch (e) {
      logger.e('Error loading products: $e');
      Get.snackbar('Error', 'Failed to load products');
    } finally {
      isProductLoading.value = false;
      hasLoadedOnce = true;
      update();
    }
  }

  // ---------------------------------------------------------
  // Local Search Filter
  // ---------------------------------------------------------
  void applySearch(String keyword) {
    if (keyword.isEmpty) {
      product.assignAll(masterProductList);
      update();
      return;
    }

    final filtered = masterProductList.where((p) {
      return (p.productname ?? "")
          .toLowerCase()
          .contains(keyword.toLowerCase());
    }).toList();

    product.assignAll(filtered);
    update();
  }

  // ---------------------------------------------------------
  // Update Product (API)
  // ---------------------------------------------------------
  Future<void> updateProductStatus(ProductUpdateRequest data) async {
    try {
      final result = await productsRepository.productUpdate(data);
      logger.i('Product Update: ${result?.message}');

      if (result?.status != true) {
        Get.snackbar('Failed', result?.message ?? 'Update failed');
      }
    } catch (e) {
      logger.e('Update Exception: $e');
      Get.snackbar('Error', 'Network error');
      rethrow;
    }
  }

  Future<void> updateProduct(int productlocationid, String status) async {
    await updateProductStatus(
      ProductUpdateRequest(
        productid: productlocationid,
        productstatus: status,
      ),
    );
  }

  // ---------------------------------------------------------
  // Order → Product Details
  // ---------------------------------------------------------
  Future<void> getProductDetails(int orderHeaderId) async {
    productDetail.clear();

    try {
      final result = await productsRepository.getProductDetail(orderHeaderId);
      productDetail.assignAll(result?.details ?? []);
      logger.i('Order ProductDetails loaded: ${productDetail.length}');
    } catch (e) {
      logger.e('Failed loading details: $e');
      Get.snackbar('Error', 'Could not load items');
    }
  }
}
