import 'package:cheminova/models/product_model1.dart';
import 'package:cheminova/screens/product/cart_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../controller/cart_controller.dart';
import '../../widgets/my_drawer.dart';
import '../../widgets/product_card.dart';
import '../../controller/product_service.dart';

// ProductCatalogScreen displays a catalog of products that users can browse and filter.
class ProductCatalogScreen extends StatefulWidget {
  const ProductCatalogScreen({super.key});

  @override
  State<ProductCatalogScreen> createState() => _ProductCatalogScreenState();
}

class _ProductCatalogScreenState extends State<ProductCatalogScreen> {
  final ProductService _productService = ProductService(); // Service to fetch product data.
  final ScrollController _scrollController = ScrollController(); // Controller for scroll events.
  final CartController cartController = Get.put(CartController()); // Cart controller for managing cart state.

  List<Product> _products = []; // List to hold the fetched products.
  List<Map<String, dynamic>> _categories = []; // List to hold product categories.

  int _currentPage = 1; // Tracks the current page of products being fetched.
  bool _isLoading = false; // Indicates if data is being loaded.
  bool _hasMoreData = true; // Indicates if more data can be fetched.

  String? _selectedCategory; // Tracks the currently selected category for filtering.
  String? _selectedPriceRange; // Placeholder for selected price range filtering.
  String? _selectedAvailability; // Placeholder for selected availability filtering.

  @override
  void initState() {
    super.initState();
    _fetchCategories(); // Fetch categories on initialization.
    _fetchProducts(); // Fetch initial products.

    // Add listener to fetch more products when reaching the bottom of the scroll view.
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent &&
          !_isLoading && _hasMoreData) {
        _fetchMoreProducts();
      }
    });
  }

  // Fetch products from the server.
  Future<void> _fetchProducts() async {
    setState(() {
      _isLoading = true; // Set loading to true while fetching data.
    });

    final category = _selectedCategory == 'All' ? null : _selectedCategory; // Adjust category filter.

    // Get products using the product service.
    final products = await _productService.getProduct(
        _currentPage, category: category);
    setState(() {
      if (products != null) {
        _products.addAll(products); // Append fetched products to the list.
        _hasMoreData = products.isNotEmpty; // Update the flag for more data availability.
      }
      _isLoading = false; // Set loading to false after fetching data.
    });
  }

  // Fetch available product categories.
  Future<void> _fetchCategories() async {
    final categories = await _productService.getCategory(); // Fetch categories.
    if (categories != null) {
      setState(() {
        _categories = categories; // Set the fetched categories.
        _categories.insert(1, {'categoryName': 'All'}); // Add 'All' category option.
        _selectedCategory = 'All'; // Default selected category.
      });
    }
  }

  // Handle category changes when the user selects a new category.
  void _onCategoryChanged(String? newCategory) {
    if (newCategory != null) {
      setState(() {
        _selectedCategory = newCategory; // Update selected category.
        _products.clear(); // Clear current product list for new fetch.
        _currentPage = 1; // Reset page counter.
      });
      _fetchProducts(); // Fetch products for the selected category.
    }
  }

  // Fetch additional products when scrolling to the bottom.
  Future<void> _fetchMoreProducts() async {
    if (!_isLoading && _hasMoreData) { // Ensure not already loading and more data is available.
      setState(() {
        _isLoading = true; // Set loading to true while fetching more products.
        _currentPage++; // Increment the page number for next fetch.
      });
      await _fetchProducts(); // Fetch more products.
    }
  }

  // Clear all filters and reset the product list.
  void _clearFilters() {
    setState(() {
      _selectedCategory = null; // Reset category filter.
      _selectedPriceRange = null; // Reset price range filter.
      _selectedAvailability = null; // Reset availability filter.
      _products.clear(); // Clear current product list.
      _currentPage = 1; // Reset page counter.
    });
    _fetchProducts(); // Fetch products without filters.
  }

  @override
  void dispose() {
    _scrollController.dispose(); // Dispose of the scroll controller when done.
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent, // Make the AppBar transparent.
        elevation: 0, // No shadow for the AppBar.
        leading: Builder(
          builder: (context) {
            return GestureDetector(
              onTap: () => Scaffold.of(context).openDrawer(), // Open drawer on tap.
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: SvgPicture.asset(
                  'assets/svg/menu.svg', // Menu icon.
                ),
              ),
            );
          },
        ),
        actions: [
          // Cart icon with count indicator.
          GestureDetector(
            onTap: () => Get.to(CartScreen()), // Navigate to cart on tap.
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Stack(
                children: [
                  const Icon(Icons.shopping_cart, size: 30,), // Shopping cart icon.
                  // Cart count display
                  Positioned(
                    right: 0,
                    child: Obx(() =>
                    cartController.cartCount.value > 0
                        ? Container(
                      padding: const EdgeInsets.all(4),
                      decoration: const BoxDecoration(
                        color: Colors.red,
                        shape: BoxShape.circle,
                      ),
                      child: Text(
                        '${cartController.cartCount.value}', // Display number of items in cart.
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                      ),
                    )
                        : const SizedBox.shrink()), // Hide if cart is empty.
                  ),
                ],
              ),
            ),
          ),
        ],
        title: const Center(
          child: Text(
            "Product Catalogue", // Title of the screen.
          ),
        ),
      ),
      drawer: const MyDrawer(), // Navigation drawer.
      body: Stack(
        fit: StackFit.expand,
        children: [
          // Background image for the screen.
          Image.asset(
            'assets/images/image_1.png',
            fit: BoxFit.cover,
          ),
          SafeArea(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  SizedBox(height: Get.height * 0.02), // Spacing.

                  // Search bar for products.
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 18.0),
                    child: TextField(
                      decoration: InputDecoration(
                        hintText: "Search Products", // Placeholder for search.
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(15),
                        ),
                        filled: true,
                        fillColor: Colors.white.withOpacity(0.9),
                      ),
                    ),
                  ),
                  SizedBox(height: Get.height * 0.02), // Spacing.

                  // Card for filters and product listing.
                  Card(
                    margin: const EdgeInsets.symmetric(horizontal: 18),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(19),
                      side: const BorderSide(color: Color(0xFFFDFDFD)),
                    ),
                    color: const Color(0xFFB4D1E5).withOpacity(0.9),
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          // Filter section header.
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "Filter", // Filter title.
                                style: GoogleFonts.poppins(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16,
                                ),
                              ),
                              // Button to clear filters.
                              TextButton(
                                onPressed: _clearFilters,
                                child: Text(
                                  "Clear Filter", // Clear filters button text.
                                  style: GoogleFonts.poppins(
                                    color: Colors.red,
                                    fontSize: 14,
                                  ),
                                ),
                              ),
                            ],
                          ),

                          // Dropdowns for filtering options.
                          SizedBox(
                            height: Get.height * 0.05,
                            child: ListView.builder(
                              shrinkWrap: true,
                              scrollDirection: Axis.horizontal,
                              itemCount: 3, // Number of filters (categories, etc.).
                              itemBuilder: (context, index) =>
                                  _buildFilterDropdown(index), // Build filter dropdowns.
                            ),
                          ),

                          // List of products.
                          SizedBox(
                            height: Get.height * 0.6,
                            child: ListView.builder(
                              controller: _scrollController, // Attach scroll controller.
                              padding: EdgeInsets.zero,
                              itemCount: _products.length + (_isLoading ? 1 : 0), // Show loading indicator if more products are being fetched.
                              itemBuilder: (context, index) {
                                if (index >= _products.length) {
                                  print("Product length $_products");
                                  return const Center(
                                      child: CircularProgressIndicator()); // Show loading indicator.
                                }
                                // Display each product card.
                                return Padding(
                                  padding: const EdgeInsets.symmetric(vertical: 8),
                                  child: ProductCard(
                                    productModel: _products[index], // Use ProductModel here.
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // Build a dropdown for filtering based on the index.
  Widget _buildFilterDropdown(int index) {
    switch (index) {
      case 0:
        return _buildStyledDropdown(
          value: _selectedCategory,
          onChanged: _onCategoryChanged,
          items: _categories.map((category) {
            return DropdownMenuItem<String>(
              value: category['categoryName'],
              child: Text(category['categoryName']),
            );
          }).toList(),
          hint: "Category", // Dropdown hint for category selection.
        );
      default:
        return const SizedBox(); // Return empty widget for unsupported indices.
    }
  }

  // Build a styled dropdown widget.
  Widget _buildStyledDropdown({
    required String? value,
    required ValueChanged<String?> onChanged,
    required List<DropdownMenuItem<String>> items,
    required String hint,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: Colors.grey.shade300),
        color: Colors.white,
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          value: value,
          onChanged: onChanged,
          items: items,
          hint: Text(hint),
          icon: const Icon(Icons.arrow_drop_down), // Dropdown arrow icon.
        ),
      ),
    );
  }
}
