import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';
import 'package:nearledaily/constants/color_constants.dart';
import 'package:nearledaily/view/product/product_view.dart';
import 'package:shimmer/shimmer.dart';
import '../../constants/asset_constants.dart';
import '../../constants/font_constants.dart';
import '../../controllers/cart_controller/cart.dart';
import '../../controllers/product/product_controller.dart';
import '../../controllers/product/variant_controller.dart';
import '../../domain/provider/varient/varient_pro.dart';
import '../../modules/product/product.dart';
import '../../service/firebase_analytics/analytics_service.dart';
import '../../widgets/text_widget.dart';
import '../cart/cart_view.dart';
import '../home_view.dart';

class ProductsScreen extends StatelessWidget {
  final int categoryId;
  final int tenantId;
  final int locationId;
  final int tenantloc;
  final String tenantName;
  final String locationname;
  final String tenantLocation;
  final String tenantImage;
  final String subCategoryName; // 👈 added

  bool ss = false;

  ProductsScreen({
    Key? key,
    required this.categoryId,
    required this.tenantId,
    required this.locationId,
    required this.tenantloc,
    required this.tenantName,
    required this.locationname,
    required this.tenantLocation,
    required this.tenantImage,
    required this.subCategoryName, // 👈 required param
  }) : super(key: key);

  final ProductsController controller =
  Get.put(ProductsController(), permanent: false);

  final variantController = Get.put(
    ProductVariantController(provider: ProductVariantProvider()),
  );
  final CartController cartController = Get.put(CartController());

  final provider = ProductVariantProvider();

  // ─── Tablet helpers ────────────────────────────────────────────────────────

  /// Anything wider than 600 logical pixels is treated as a tablet.
  bool _isTablet(BuildContext context) =>
      MediaQuery.of(context).size.shortestSide >= 600;

  /// Number of grid columns: 3 on tablet, 2 on phone.
  int _crossAxisCount(BuildContext context) => _isTablet(context) ? 3 : 2;

  /// Grid aspect ratio: slightly taller cards work better on a 3-col tablet grid.
  double _childAspectRatio(BuildContext context) =>
      _isTablet(context) ? 0.66 : 0.65;

  /// Category chip width: wider on tablet.
  double _chipWidth(BuildContext context) => _isTablet(context) ? 170.0 : 140.0;

  /// Responsive font scaling (reference width 390 for phone, 768 for tablet).
  double _scaleFont(BuildContext context, double size) {
    final screenWidth = MediaQuery.of(context).size.width;
    final referenceWidth = _isTablet(context) ? 768.0 : 390.0;
    return size * (screenWidth / referenceWidth);
  }

  // ───────────────────────────────────────────────────────────────────────────

  @override
  Widget build(BuildContext context) {

    

    controller.fetchProducts(categoryId, tenantId, tenantloc);

    final isTablet = _isTablet(context);

    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: const SystemUiOverlayStyle(
        statusBarColor: Colors.white,
        statusBarIconBrightness: Brightness.light,   // Android
        statusBarBrightness: Brightness.light,       // iOS
      ),
      child: SafeArea(
        child: Scaffold(
          floatingActionButton: Obx(() {
        
            if (cartController.totalItems == 0) {
              return const SizedBox(); // Hide FAB when cart is empty
            }
        
            return FloatingActionButton.extended(
              onPressed: () {
        
                Get.to(CartPage());
        
              },
              backgroundColor: const Color(0xFF662582),
              icon: const Icon(Icons.shopping_cart, color: Colors.white),
              label: Text(
                "View Cart (${cartController.totalItems})",
                style: const TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
            );
          }),        backgroundColor: Colors.white,
          appBar: AppBar(
            surfaceTintColor: Colors.transparent,
        
            scrolledUnderElevation: 0,
            animateColor: false,
            elevation: 0,
            backgroundColor: Color(0xFF662582),
            automaticallyImplyLeading: false,
            title: Obx(() {
              return AnimatedSwitcher(
                duration: const Duration(milliseconds: 200),
                transitionBuilder: (child, anim) => SizeTransition(
                    sizeFactor: anim, axis: Axis.horizontal, child: child),
                child: controller.isSearching.value
                    ? Container(
                  key: const ValueKey("searchBar"),
                  height: 45,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(25),
                  ),
                  child: TextField(
                    autofocus: true,
                    onChanged: (value) =>
                    controller.searchQuery.value = value,
                    decoration: InputDecoration(
                      hintText: "Search products...",
                      hintStyle: TextStyle(
                          color: Colors.grey.shade500, fontSize: 14),
                      prefixIcon: const Icon(Icons.search,
                          color: Colors.deepPurple),
                      border: InputBorder.none,
                      contentPadding:
                      const EdgeInsets.symmetric(vertical: 10),
                    ),
                  ),
                )
                    : Row(
                  key: const ValueKey("tenantInfo"),
                  children: [
                    IconButton(
                      icon: const Icon(Icons.arrow_back,color: Colors.white,),
                      onPressed: () => Navigator.pop(context),
                    ),
                    const SizedBox(width: 4),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        ReusableTextWidget(
                          text: tenantName,
                          color: Colors.white,
                          fontFamily: FontConstants.fontFamily,
                          // ✅ Slightly larger on tablet
                          fontSize: isTablet ? 18 : 16,
                          fontWeight: FontWeight.w700,
                          textAlign: TextAlign.start,
                          maxLines: 1,
                        ),
                        ReusableTextWidget(
                          text: locationname,
                          color: Colors.white,
                          fontFamily: FontConstants.fontFamily,
                          // ✅ Slightly larger on tablet
                          fontSize: isTablet ? 15 : 13,
                          fontWeight: FontWeight.w500,
                          textAlign: TextAlign.start,
                          maxLines: 1,
                        ),
                      ],
                    ),
                  ],
                ),
              );
            }),
            actions: [
              Obx(() {
                return controller.isSearching.value
                    ? IconButton(
                  icon:
                  const Icon(Icons.close, color: Colors.redAccent),
                  onPressed: () {
                    controller.isSearching.value = false;
                    controller.searchQuery.value = '';
                  },
                )
                    : IconButton(
                  icon: const Icon(Icons.search,
                      color: Colors.white),
                  onPressed: () =>
                  controller.isSearching.value = true,
                );
              }),
            ],
          ),
          body: Stack(
            children: [
              Obx(() {
                if (!controller.isConnected.value) {
                  return Center(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(Icons.wifi_off, size: 80, color: Colors.grey),
                        SizedBox(height: 16),
                        ReusableTextWidget(
                          text: 'No Internet Connection',
                          color: Colors.grey[700]!,
                          fontFamily: FontConstants.fontFamily,
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                          textAlign: TextAlign.center,
                        ),
                      ],
                    ),
                  );
                }
        
                if (controller.isLoading.value) {
                  return productsShimmer(context);
                }
        
                final details =
                    controller.productResponse.value?.data?.details ?? [];
                if (details.isEmpty) {
                  controller.fetchProducts(categoryId, tenantId, tenantloc);
                  return Center(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        SizedBox(height: 50),
                        Image.asset(
                          AssetConstants.noDataProducts,
                          height: 100,
                          width: 130,
                          fit: BoxFit.fill,
                        ),
                        ReusableTextWidget(
                          text: 'No Products Yet',
                          color: ColorConstants.blackColor,
                          fontFamily: FontConstants.fontFamily,
                          fontSize: 18,
                          fontWeight: FontWeight.w700,
                          maxLines: 2,
                          textAlign: TextAlign.center,
                        ),
                      ],
                    ),
                  );
                }
        
                return Column(
                  children: [
        
                    SizedBox(
                      height: isTablet ? 200 : 120,
                      child: Container(
                        decoration: BoxDecoration(
                            color: const Color(0xFF662582),
                          borderRadius: BorderRadius.only(
                            bottomRight: Radius.circular(40),
                            bottomLeft: Radius.circular(40)
                          )
                        ),
        
                        child: Obx(() {
                          final details =
                              controller.productResponse.value?.data?.details ?? [];
                          if (details.isEmpty) return const SizedBox();
        
                          return ListView.separated(
                            padding: const EdgeInsets.symmetric(horizontal: 12),
                            scrollDirection: Axis.horizontal,
                            physics: const BouncingScrollPhysics(),
                            itemCount: details.length,
                            separatorBuilder: (_, __) => const SizedBox(width: 6),
                            itemBuilder: (context, index) {
                              final sub = details[index];
        
                              return TweenAnimationBuilder<double>(
                                duration: Duration(milliseconds: 300 + (index * 50)),
                                tween: Tween(begin: 0.0, end: 1.0),
                                curve: Curves.easeOutCubic,
                                builder: (context, animValue, child) {
                                  return Transform.translate(
                                    offset: Offset(0, 10 * (1 - animValue)),
                                    child: Opacity(opacity: animValue, child: child),
                                  );
                                },
                                child: Obx(() {
                                  final isSelected =
                                      controller.selectedIndex.value == index;
        
                                  return GestureDetector(
                                    onTap: () {
                                      controller.selectedIndex.value = index;
                                      controller.searchQuery.value = '';
                                    },
                                    child: AnimatedContainer(
                                      duration: const Duration(milliseconds: 250),
                                      curve: Curves.easeInOutCubic,
        
                                      // ✅ FIXED WIDTH FOR ALL
                                      width: isTablet ? 100 : 80,
        
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 6,
                                        vertical: isTablet ? 10 : 8,
                                      ),
        
                                      decoration: BoxDecoration(
                                        color: Colors.transparent,
                                        // border: Border(
                                        //   bottom: BorderSide(
                                        //     color: isSelected
                                        //         ? Colors.white
                                        //         : Colors.transparent,
                                        //     width: 3.5
                                        //   ),
                                        // ),
                                      ),
        
                                      child: Column(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          // 🔥 ICON
                                          AnimatedOpacity(
                                            duration: const Duration(milliseconds: 250),
                                            curve: Curves.easeInOut,
                                            opacity: isSelected ? 1.0 : 1.0,
                                            child: AnimatedScale(
                                              duration: const Duration(milliseconds: 250),
                                              scale: isSelected ? 1.0 : 0.9,
                                              child: Container(
                                                height: 60,
                                                width: 60,
                                                decoration: BoxDecoration(
                                                  shape: BoxShape.circle,
                                                  color: Colors.grey.shade200, // background
                                                ),
                                                child: ClipOval(
                                                  child: Image.network(
                                                    sub.image ?? '',
                                                    fit: BoxFit.cover, // 🔥 IMPORTANT for circle fill
        
                                                    loadingBuilder: (context, child, progress) {
                                                      if (progress == null) return child;
                                                      return const Center(
                                                        child: CircularProgressIndicator(strokeWidth: 2),
                                                      );
                                                    },
        
                                                    errorBuilder: (context, error, stackTrace) {
                                                      return const Center(
                                                        child: Icon(
                                                          Icons.image_not_supported,
                                                          color: Colors.grey,
                                                        ),
                                                      );
                                                    },
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ),
        
                                          const SizedBox(height: 6),
        
                                          // 🔥 TEXT (FIXED + ELLIPSIS)
                                          SizedBox(
                                            width: double.infinity,
                                            child: AnimatedDefaultTextStyle(
                                              duration:
                                              const Duration(milliseconds: 200),
                                              style: TextStyle(
                                                fontSize: isTablet
                                                    ? (isSelected ? 13 : 12)
                                                    : (isSelected ? 12 : 11),
                                                fontWeight: isSelected
                                                    ? FontWeight.w700
                                                    : FontWeight.w500,
                                                color: isSelected
                                                    ? Colors.white
                                                    : Colors.white60,
                                              ),
                                              child: Text(
                                                sub.subcategoryname ?? "",
                                                overflow: TextOverflow.ellipsis,
                                                maxLines: 1,
                                                textAlign: TextAlign.center,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                }),
                              );
                            },
                          );
                        }),
                      ),
                    ),
        
                    // ── Product grid ─────────────────────────────────────
                    Expanded(
                      child: LayoutBuilder(
                        builder: (context, constraints) {
                          // ✅ Responsive columns & image height
                          final crossAxisCount = _crossAxisCount(context);
                          final itemWidth =
                              constraints.maxWidth / crossAxisCount;
                          final imageHeight = itemWidth * 0.75;
        
                          double scaleButtonWidth(double w) => w * 0.5;
                          double scaleButtonHeight(double h) => h * 0.06;
        
                          return Obx(() {
                            final products = controller.filteredProducts;
                            if (products.isEmpty) {
                              return Center(
                                child: Column(
                                  mainAxisAlignment:
                                  MainAxisAlignment.center,
                                  children: [
                                    Lottie.asset(
                                      'assets/lotties/empty.json',
                                      width: 200,
                                      height: 200,
                                      fit: BoxFit.contain,
                                    ),
                                    const SizedBox(height: 20),
                                    const Text(
                                      "No products found",
                                      style: TextStyle(
                                          fontSize: 16,
                                          fontWeight: FontWeight.w500),
                                    ),
                                  ],
                                ),
                              );
                            }
        
                            return GridView.builder(
                              padding: const EdgeInsets.all(12),
                              itemCount: controller.filteredProducts.length,
                              gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(
                                // ✅ 3 columns on tablet, 2 on phone
                                crossAxisCount: crossAxisCount,
                                crossAxisSpacing: 10,
                                mainAxisSpacing: 10,
                                childAspectRatio:
                                _childAspectRatio(context),
                              ),
                              itemBuilder: (context, index) {
                                final product =
                                controller.filteredProducts[index];
                                print(product);
                                final status = product.productstatus
                                    ?.toString()
                                    .toUpperCase() ??
                                    "";
                                final inStock =
                                    status.contains("ACTIVE") ||
                                        status.contains("AVAILABLE");
                                print(inStock);
        
                                return GestureDetector(
                                  onTap: () async {
        
                                    await AnalyticsService.logEvent(
                                      'product_viewed',
                                      parameters: {
                                        'product_id': product.productid ?? 0,
                                        'product_name': product.productname ?? '',
                                        'tenant_id': product.tenantid ?? 0,
                                      },
                                    );
        
                                    Get.to(() => ProductViewPage(
                                      product: product,
                                      tenantImage: tenantImage,
                                      tenantName: tenantName,
                                      tenantId: tenantId,
                                      locationId: locationId,
                                    ));
        
                                  },
                                  child: Container(
                                    decoration: BoxDecoration(
                                      // color: Colors.white,
                                      // borderRadius:
                                      // BorderRadius.circular(7),
                                      // border: Border.all(
                                      //     color: Colors.black12,
                                      //     width: 0.20),
                                      // boxShadow: [
                                      //   BoxShadow(
                                      //     color: Colors.black12,
                                      //     blurRadius: 6,
                                      //     offset: const Offset(2, 2),
                                      //   ),
                                      // ],
                                    ),
                                    child: Column(
                                      crossAxisAlignment:
                                      CrossAxisAlignment.start,
                                      children: [
                                        // 🔹 Product Image
                                        Container(
                                          margin:
                                          const EdgeInsets.symmetric(
                                              horizontal: 5,
                                              vertical: 5),
                                          child: ClipRRect(
                                            borderRadius:
                                            const BorderRadius.all(Radius.circular(17)),
                                            child: Stack(
                                              alignment: Alignment.center,
                                              children: [
                                                ColorFiltered(
                                                  colorFilter: inStock
                                                      ? const ColorFilter
                                                      .mode(
                                                    Colors.transparent,
                                                    BlendMode.multiply,
                                                  )
                                                      : const ColorFilter
                                                      .matrix([
                                                    0.2126, 0.7152,
                                                    0.0722, 0, 0,
                                                    0.2126, 0.7152,
                                                    0.0722, 0, 0,
                                                    0.2126, 0.7152,
                                                    0.0722, 0, 0,
                                                    0, 0, 0, 1, 0,
                                                  ]),
                                                  child: Image.network(
                                                    product.productimage ??
                                                        '',
                                                    // ✅ imageHeight is now
                                                    // computed per column count
                                                    height: imageHeight,
                                                    width: double.infinity,
                                                    fit: BoxFit.cover,
                                                    loadingBuilder: (context,
                                                        child,
                                                        loadingProgress) {
                                                      if (loadingProgress ==
                                                          null) return child;
                                                      return Shimmer
                                                          .fromColors(
                                                        baseColor: Colors
                                                            .grey[300]!,
                                                        highlightColor:
                                                        Colors
                                                            .grey[100]!,
                                                        child: Container(
                                                          height:
                                                          imageHeight,
                                                          color:
                                                          Colors.white,
                                                        ),
                                                      );
                                                    },
                                                    errorBuilder: (context,
                                                        error, stackTrace) {
                                                      return Container(
                                                        height: imageHeight,
                                                        width:
                                                        double.infinity,
                                                        color:
                                                        Colors.grey[300],
                                                        child: const Icon(
                                                            Icons.image,
                                                            size: 48,
                                                            color:
                                                            Colors.grey),
                                                      );
                                                    },
                                                  ),
                                                ),
        
                                                if (!inStock)
                                                  Container(
                                                    height: imageHeight,
                                                    width: double.infinity,
                                                    color: Colors.grey
                                                        .withOpacity(0.10),
                                                  ),
        
        
                                              ],
                                            ),
                                          ),
                                        ),
        
                                        // 🔹 Product Info
                                        Padding(
                                          padding: const EdgeInsets
                                              .symmetric(horizontal: 10),
                                          child: Column(
                                            crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                            children: [
                                              ReusableTextWidget(
                                                text: product.productname ??
                                                    "No name",
                                                color: Colors.black
                                                    .withOpacity(0.7),
                                                fontFamily:
                                                FontConstants.fontFamily,
                                                // ✅ Scaled font
                                                fontSize: _scaleFont(
                                                    context, 14),
                                                fontWeight: FontWeight.bold,
                                                textAlign: TextAlign.start,
                                                maxLines: 1,
                                                overflow:
                                                TextOverflow.ellipsis,
                                              ),
        
        
        
        
        
                                              const SizedBox(height: 4),
        
                                              Row(
                                                children: [
                                                  Flexible(
                                                    child: ReusableTextWidget(
                                                      text:
                                                      "₹${(product.productcost ?? 0) - (product.discount ?? 0)}",
                                                      color: Colors.black
                                                          .withOpacity(0.7),
                                                      fontFamily: FontConstants
                                                          .fontFamily,
                                                      fontSize: _scaleFont(
                                                          context, 15),
                                                      fontWeight:
                                                      FontWeight.w600,
                                                      textAlign:
                                                      TextAlign.start,
                                                    ),
                                                  ),
        
                                                  SizedBox(width: 5),
        
                                                  if ((product.discount ??
                                                      0) >
                                                      0)
                                                    Flexible(
                                                      child:
                                                      ReusableTextWidget(
                                                        text:
                                                        "₹${product.productcost ?? 0}",
                                                        color: Colors.red,
                                                        fontFamily:
                                                        FontConstants
                                                            .fontFamily,
                                                        fontSize: _scaleFont(
                                                            context, 15),
                                                        fontWeight:
                                                        FontWeight.w600,
                                                        textAlign:
                                                        TextAlign.start,
                                                        isUnderText:
                                                        TextDecoration
                                                            .lineThrough,
                                                      ),
                                                    ),
        
        
                                                  const SizedBox(width: 5),
                                                ],
                                              ),
                                              if (!inStock)
                                                Text(
                                                  'Out of stock',
                                                  style: TextStyle(
                                                    color: Colors.red,
                                                    // ✅ Slightly larger
                                                    // OOS label on tablet
                                                    fontSize: isTablet
                                                        ? 15
                                                        : 14,
                                                    fontWeight:
                                                    FontWeight.w500,
                                                    letterSpacing: 0.4,
                                                  ),
                                                ),
        
                                            ],
                                          ),
                                        ),
        
                                        // 🔹 Bottom Row — More Details + Add Button
                                        Padding(
                                          padding: const EdgeInsets.symmetric(
                                              horizontal: 10, vertical: 6),
                                          child: Row(
                                            crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                            mainAxisAlignment:
                                            MainAxisAlignment
                                                .spaceBetween,
                                            children: [
                                              Expanded(
                                                child: InkWell(
                                                  onTap: () async {
        
                                                    await AnalyticsService.logEvent(
                                                      'product_viewed',
                                                      parameters: {
                                                        'product_id': product.productid ?? 0,
                                                        'product_name': product.productname ?? '',
                                                        'tenant_id': product.tenantid ?? 0,
                                                      },
                                                    );
        
                                                    Get.to(() =>
                                                        ProductViewPage(
                                                          product: product,
                                                          tenantImage:
                                                          tenantImage,
                                                          tenantName:
                                                          tenantName,
                                                          tenantId: tenantId,
                                                          locationId:
                                                          locationId,
                                                        ));
                                                  },
                                                  child: Row(
                                                    children: [
                                                      ReusableTextWidget(
                                                        text:
                                                        "${product.unitvalue ?? 0} ${productunitValues.reverse[product.productunit ?? 0] ?? ''}",
                                                        color: Colors.black
                                                            .withOpacity(0.7),
                                                        fontFamily:
                                                        FontConstants
                                                            .fontFamily,
                                                        fontSize: _scaleFont(
                                                            context, 14),
                                                        fontWeight:
                                                        FontWeight.w500,
                                                        textAlign:
                                                        TextAlign.start,
                                                      ),
                                                      const SizedBox(
                                                          width: 3),
                                                      const Icon(
                                                          Icons
                                                              .arrow_forward_ios,
                                                          size: 12,
                                                          color: Colors.grey),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                              const SizedBox(width: 6),
        
                                              // Add button
                                              InkWell(
                                                onTap: () async {
                                                  if (inStock) {
                                                    variantController
                                                        .clearVariantState();
                                                    await variantController
                                                        .fetchVariants(
                                                      tenantId:
                                                      product.tenantid!,
                                                      variantId:
                                                      product.variants!,
                                                    );
        
                                                    Get.bottomSheet(
                                                      Container(
                                                        decoration:
                                                        BoxDecoration(
                                                          color: Colors
                                                              .grey.shade200,
                                                          borderRadius:
                                                          const BorderRadius
                                                              .vertical(
                                                            top: Radius
                                                                .circular(12),
                                                          ),
                                                        ),
                                                        padding:
                                                        const EdgeInsets
                                                            .all(16),
                                                        child: Column(
                                                          mainAxisSize:
                                                          MainAxisSize
                                                              .min,
                                                          children: [
                                                            Row(
                                                              mainAxisAlignment:
                                                              MainAxisAlignment
                                                                  .spaceBetween,
                                                              children: [
                                                                Text(
                                                                  product
                                                                      .productname!,
                                                                  style: TextStyle(
                                                                      fontSize: isTablet
                                                                          ? 21
                                                                          : 19,
                                                                      fontWeight:
                                                                      FontWeight.w700),
                                                                ),
                                                                IconButton(
                                                                  onPressed:
                                                                      () {
                                                                    Navigator.of(
                                                                        context)
                                                                        .pop();
                                                                  },
                                                                  icon:
                                                                  const Icon(
                                                                      Icons
                                                                          .close),
                                                                ),
                                                              ],
                                                            ),
                                                            const SizedBox(
                                                                height: 20),
        
                                                            Flexible(
                                                              child: Obx(() {
                                                                if (variantController
                                                                    .isLoading
                                                                    .value) {
                                                                  return const SizedBox(
                                                                    height:
                                                                    200,
                                                                    child: Center(
                                                                        child:
                                                                        CircularProgressIndicator()),
                                                                  );
                                                                }
        
                                                                if (variantController
                                                                    .productVariants
                                                                    .isEmpty) {
                                                                  return const SizedBox(
                                                                    height:
                                                                    100,
                                                                    child: Center(
                                                                        child: Text(
                                                                            "No variants found")),
                                                                  );
                                                                }
        
                                                                return ListView
                                                                    .builder(
                                                                  shrinkWrap:
                                                                  true,
                                                                  itemCount:
                                                                  variantController
                                                                      .productVariants
                                                                      .length,
                                                                  itemBuilder:
                                                                      (context,
                                                                      index) {
                                                                    final variant =
                                                                    variantController
                                                                        .productVariants[index];
        
                                                                    return Obx(
                                                                            () {
                                                                          final selectedId =
                                                                              variantController
                                                                                  .selectedProductId
                                                                                  .value;
                                                                          final isSelected =
                                                                              selectedId ==
                                                                                  variant.productid;
        
                                                                          return Container(
                                                                            margin: const EdgeInsets
                                                                                .symmetric(
                                                                                vertical:
                                                                                6),
                                                                            padding: const EdgeInsets
                                                                                .all(
                                                                                12),
                                                                            decoration:
                                                                            BoxDecoration(
                                                                              color:
                                                                              Colors.white,
                                                                              borderRadius:
                                                                              BorderRadius.circular(12),
                                                                              boxShadow: [
                                                                                BoxShadow(
                                                                                  color: Colors.black.withOpacity(0.08),
                                                                                  blurRadius: 6,
                                                                                  offset: const Offset(0, 3),
                                                                                ),
                                                                              ],
                                                                            ),
                                                                            child:
                                                                            Row(
                                                                              children: [
                                                                                ClipRRect(
                                                                                  borderRadius: BorderRadius.circular(8),
                                                                                  child: Image.network(
                                                                                    variant.productimage ?? '',
                                                                                    // ✅ Bigger variant thumbnails on tablet
                                                                                    height: isTablet ? 80 : 65,
                                                                                    width: isTablet ? 80 : 65,
                                                                                    fit: BoxFit.cover,
                                                                                    errorBuilder: (_, __, ___) => Container(
                                                                                      height: isTablet ? 80 : 65,
                                                                                      width: isTablet ? 80 : 65,
                                                                                      color: Colors.grey[300],
                                                                                      child: const Icon(Icons.image, color: Colors.grey),
                                                                                    ),
                                                                                  ),
                                                                                ),
                                                                                const SizedBox(width: 12),
                                                                                Expanded(
                                                                                  child:
                                                                                  Column(
                                                                                    crossAxisAlignment: CrossAxisAlignment.start,
                                                                                    children: [
                                                                                      Text(
                                                                                        variant.productname ?? '',
                                                                                        style: TextStyle(
                                                                                          // ✅ Larger variant name on tablet
                                                                                          fontSize: isTablet ? 18 : 16,
                                                                                          fontWeight: FontWeight.w600,
                                                                                        ),
                                                                                      ),
                                                                                      const SizedBox(height: 4),
                                                                                      Row(
                                                                                        children: [
                                                                                          Text(
                                                                                            "₹${((variant.productcost ?? 0) - (variant.discount ?? 0)).toStringAsFixed(1)}",
                                                                                            style: TextStyle(
                                                                                              fontSize: isTablet ? 17 : 15,
                                                                                              fontWeight: FontWeight.bold,
                                                                                              color: Colors.black,
                                                                                            ),
                                                                                          ),
                                                                                          const SizedBox(width: 8),
                                                                                          if ((variant.discount ?? 0) > 0)
                                                                                            Text(
                                                                                              "₹${variant.productcost!.toInt()}",
                                                                                              style: TextStyle(
                                                                                                fontSize: isTablet ? 17 : 15,
                                                                                                fontWeight: FontWeight.bold,
                                                                                                color: Colors.red,
                                                                                                decoration: TextDecoration.lineThrough,
                                                                                              ),
                                                                                            ),
                                                                                        ],
                                                                                      ),
                                                                                    ],
                                                                                  ),
                                                                                ),
                                                                                Checkbox(
                                                                                  value:
                                                                                  isSelected,
                                                                                  onChanged:
                                                                                      (val) {
                                                                                    variantController.selectVariant(variant.productid!);
                                                                                  },
                                                                                ),
                                                                              ],
                                                                            ),
                                                                          );
                                                                        });
                                                                  },
                                                                );
                                                              }),
                                                            ),
                                                            const SizedBox(
                                                                height: 20),
        
                                                            Obx(() {
                                                              final selectedId =
                                                                  variantController
                                                                      .selectedProductId
                                                                      .value;
                                                              if (selectedId ==
                                                                  null)
                                                                return const SizedBox
                                                                    .shrink();
        
                                                              final variant =
                                                              variantController
                                                                  .productVariants
                                                                  .firstWhere(
                                                                      (v) =>
                                                                  v.productid ==
                                                                      selectedId);
                                                              final variantStatus =
                                                                  variant.productstatus
                                                                      ?.toString()
                                                                      .toUpperCase() ??
                                                                      "";
                                                              final variantInStock =
                                                                  variantStatus.contains(
                                                                      "ACTIVE") ||
                                                                      variantStatus
                                                                          .contains(
                                                                          "AVAILABLE");
        
                                                              final qty =
                                                                  variantController
                                                                      .variantQuantities[
                                                                  selectedId] ??
                                                                      1;
        
                                                              return Row(
                                                                mainAxisAlignment:
                                                                MainAxisAlignment
                                                                    .spaceBetween,
                                                                children: [
                                                                  Row(
                                                                    children: [
                                                                      IconButton(
                                                                        icon: const Icon(
                                                                            Icons
                                                                                .remove,
                                                                            color: Colors
                                                                                .redAccent),
                                                                        onPressed: variantInStock
                                                                            ? () => variantController.decreaseQuantity(selectedId)
                                                                            : null,
                                                                      ),
                                                                      Text(
                                                                        "$qty",
                                                                        style: TextStyle(
                                                                            fontSize: isTablet
                                                                                ? 18
                                                                                : 16,
                                                                            fontWeight:
                                                                            FontWeight.bold),
                                                                      ),
                                                                      IconButton(
                                                                        icon: const Icon(
                                                                            Icons
                                                                                .add,
                                                                            color: Colors
                                                                                .green),
                                                                        onPressed: variantInStock
                                                                            ? () => variantController.increaseQuantity(selectedId)
                                                                            : null,
                                                                      ),
                                                                    ],
                                                                  ),
                                                                  SizedBox(
                                                                    width: scaleButtonWidth(
                                                                        MediaQuery.of(context)
                                                                            .size
                                                                            .width),
                                                                    height: scaleButtonHeight(
                                                                        MediaQuery.of(context)
                                                                            .size
                                                                            .height),
                                                                    child:
                                                                    ElevatedButton(
                                                                      style: ElevatedButton.styleFrom(
                                                                        backgroundColor: variantInStock ? ColorConstants.primaryColor : Colors.grey.shade400,
                                                                        shape: RoundedRectangleBorder(
                                                                          borderRadius: BorderRadius.circular(8),
                                                                        ),
                                                                      ),
                                                                      onPressed:
                                                                      variantInStock
                                                                          ? () {
                                                                        final cartController = Get.find<CartController>();
                                                                        cartController.addToCart(variant, qty: qty, locationId: locationId.toString());
                                                                        print(variant);
                                                                        Navigator.of(Get.context!).pop();
                                                                        Fluttertoast.showToast(
                                                                          msg: "Added to cart",
                                                                          toastLength: Toast.LENGTH_SHORT,
                                                                          gravity: ToastGravity.BOTTOM,
                                                                          backgroundColor: Colors.green,
                                                                          textColor: Colors.white,
                                                                          fontSize: 14.0,
                                                                        );
                                                                      }
                                                                          : null,
                                                                      child:
                                                                      Text(
                                                                        variantInStock
                                                                            ? "Add to Cart"
                                                                            : "Unavailable",
                                                                        style: TextStyle(
                                                                          // ✅ Larger button text on tablet
                                                                          fontSize: isTablet ? 18 : 16,
                                                                          fontWeight: FontWeight.bold,
                                                                          color: variantInStock ? Colors.white : Colors.grey.shade700,
                                                                        ),
                                                                      ),
                                                                    ),
                                                                  ),
                                                                ],
                                                              );
                                                            }),
                                                            const SizedBox(
                                                                height: 20),
                                                          ],
                                                        ),
                                                      ),
                                                      isScrollControlled:
                                                      true,
                                                    );
                                                  } else {
                                                    final scaffoldMessenger =
                                                    ScaffoldMessenger.of(
                                                        context);
                                                    scaffoldMessenger
                                                        .clearSnackBars();
                                                    scaffoldMessenger
                                                        .showSnackBar(
                                                      SnackBar(
                                                        content: const Text(
                                                          "This item is currently unavailable",
                                                          style: TextStyle(
                                                              fontWeight:
                                                              FontWeight
                                                                  .w500,
                                                              color: Colors
                                                                  .white),
                                                        ),
                                                        backgroundColor:
                                                        Colors.redAccent
                                                            .shade700,
                                                        behavior:
                                                        SnackBarBehavior
                                                            .floating,
                                                        margin:
                                                        const EdgeInsets
                                                            .all(12),
                                                        shape: RoundedRectangleBorder(
                                                            borderRadius:
                                                            BorderRadius
                                                                .circular(
                                                                12)),
                                                        duration:
                                                        const Duration(
                                                            seconds: 4),
                                                        action: SnackBarAction(
                                                          label: "OK",
                                                          textColor:
                                                          Colors.white,
                                                          onPressed: () {
                                                            scaffoldMessenger
                                                                .hideCurrentSnackBar();
                                                          },
                                                        ),
                                                      ),
                                                    );
        
                                                    Future.delayed(
                                                        const Duration(
                                                            seconds: 2),
                                                            () {
                                                          if (scaffoldMessenger
                                                              .mounted) {
                                                            scaffoldMessenger
                                                                .hideCurrentSnackBar();
                                                          }
                                                        });
                                                  }
                                                },
                                                child: CircleAvatar(
                                                  // ✅ Slightly larger add button on tablet
                                                  radius: isTablet ? 20 : 16,
                                                  backgroundColor: inStock
                                                      ? Colors.pinkAccent
                                                      .withOpacity(0.15)
                                                      : Colors.black12,
                                                  child: Icon(
                                                    Icons.add,
                                                    // ✅ Larger icon on tablet
                                                    size: isTablet ? 22 : 18,
                                                    color: inStock
                                                        ? Colors.pinkAccent
                                                        : Colors.grey,
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                            );
                          });
                        },
                      ),
                    ),
                  ],
                );
              }),
            ],
          ),
        ),
      ),
    );
  }

  Widget productsShimmer(BuildContext context) {
    final crossAxisCount = _crossAxisCount(context);
    return GridView.builder(
      padding: const EdgeInsets.all(10),
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        // ✅ Shimmer also respects tablet column count
        crossAxisCount: crossAxisCount,
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        childAspectRatio: _childAspectRatio(context),
      ),
      itemCount: 6,
      itemBuilder: (context, index) {
        return Shimmer.fromColors(
          baseColor: Colors.grey.shade300,
          highlightColor: Colors.grey.shade100,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );
      },
    );
  }

  Widget subCategoryShimmer() {
    return SizedBox(
      height: 50,
      child: ListView.separated(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        itemCount: 6,
        separatorBuilder: (_, __) => const SizedBox(width: 10),
        itemBuilder: (context, index) {
          return Shimmer.fromColors(
            baseColor: Colors.grey.shade300,
            highlightColor: Colors.grey.shade100,
            child: Container(
              height: 40,
              width: 100,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
              ),
            ),
          );
        },
      ),
    );
  }
}