// lib/views/products/sub_category_products_screen.dart
// This is a copy of ProductsScreen but with different class name
// Used when navigating directly to a specific subcategory

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_slidable/flutter_slidable.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 '../../widgets/text_widget.dart';
import '../cart/cart_view.dart';

class SubCategoryProductsScreen 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;

  bool ss = false;

  SubCategoryProductsScreen({
    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,
  }) : super(key: key);

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

  final provider = ProductVariantProvider();

  @override
  Widget build(BuildContext context) {
    controller.fetchProducts(categoryId, tenantId, tenantloc);

    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarColor: Colors.white,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      ),
    );

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        surfaceTintColor: Colors.transparent,
        scrolledUnderElevation: 0,
        animateColor: false,
        elevation: 0,
        backgroundColor: Colors.white,
        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),
                  onPressed: () => Navigator.pop(context),
                ),
                const SizedBox(width: 4),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ReusableTextWidget(
                      text: tenantName,
                      color: Colors.black,
                      fontFamily: FontConstants.fontFamily,
                      fontSize: 16,
                      fontWeight: FontWeight.w700,
                      textAlign: TextAlign.start,
                      maxLines: 1,
                    ),
                    ReusableTextWidget(
                      text: locationname,
                      color: Colors.grey,
                      fontFamily: FontConstants.fontFamily,
                      fontSize: 13,
                      fontWeight: FontWeight.w500,
                      textAlign: TextAlign.start,
                      maxLines: 1,
                    ),
                  ],
                ),
              ],
            ),
          );
        }),

      ),

      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();
            }



            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: [


                Expanded(
                  child: LayoutBuilder(
                    builder: (context, constraints) {
                      final width = constraints.maxWidth / 2;
                      final imageHeight = width * 0.75;
                      double scaleFont(double size) {
                        return size * (MediaQuery.of(context).size.width / 390);
                      }
                      double scaleButtonWidth(double width) => width * 0.5;
                      double scaleButtonHeight(double height) => height * 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: const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            crossAxisSpacing: 10,
                            mainAxisSpacing: 10,
                            childAspectRatio: 0.68,
                          ),
                          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);

                            // The rest of your product card remains 100% unchanged
                            return GestureDetector(
                              onTap: () {
                                Get.to(() => ProductViewPage(
                                  product: product,
                                  tenantImage: tenantImage,
                                  tenantName: tenantName,
                                  tenantId: tenantId,
                                  locationId: locationId,
                                ));
                              },
                              child: Container(
                                // ... your full product card code remains exactly the same ...
                                // (image, price, discount, unit, add button, bottom sheet, etc.)
                                // I have not copied the entire 200+ lines again here to keep the response shorter
                                // but in your real file, just keep everything from "decoration:" to the end of itemBuilder
                              ),
                            );
                          },
                        );
                      });
                    },
                  ),
                ),
              ],
            );
          }),

          // Your commented-out floating cart bar remains commented out
          // Obx(() { ... })  ← unchanged
        ],
      ),
    );
  }

  Widget productsShimmer() {
    return GridView.builder(
      padding: const EdgeInsets.all(10),
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        childAspectRatio: 0.75,
      ),
      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),
              ),
            ),
          );
        },
      ),
    );
  }
}