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';
import '../../models/product_model.dart'; // Import your ProductModel

class ProductCatalogScreen extends StatefulWidget {
  const ProductCatalogScreen({super.key});

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

class _ProductCatalogScreenState extends State<ProductCatalogScreen> {
  final ProductService _productService = ProductService();
  final ScrollController _scrollController = ScrollController();
  final CartController cartController = Get.put(CartController());

  List<Product> _products = []; // Use ProductModel here
  List<Map<String, dynamic>> _categories = [];

  int _currentPage = 1;
  bool _isLoading = false;
  bool _hasMoreData = true;

  String? _selectedCategory;
  String? _selectedPriceRange;
  String? _selectedAvailability;

  @override
  void initState() {
    super.initState();
    _fetchCategories();
    _fetchProducts();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent &&
          !_isLoading &&
          _hasMoreData) {
        _fetchMoreProducts();
      }
    });
  }

  Future<void> _fetchProducts() async {
    setState(() {
      _isLoading = true;
    });

    final category = _selectedCategory == 'All' ? null : _selectedCategory;

    final products = await _productService.getProduct(
        _currentPage, category: category);
    setState(() {
      if (products != null) {
        _products.addAll(products); // Assuming products is a List<ProductModel>
        _hasMoreData = products.isNotEmpty;
      }
      _isLoading = false;
    });
  }

  Future<void> _fetchCategories() async {
    final categories = await _productService.getCategory();
    if (categories != null) {
      setState(() {
        _categories = categories;
        _categories.insert(1, {'categoryName': 'All'});
        _selectedCategory = 'All';
      });
    }
  }

  void _onCategoryChanged(String? newCategory) {
    if (newCategory != null) {
      setState(() {
        _selectedCategory = newCategory;
        _products.clear();
        _currentPage = 1;
      });
      _fetchProducts();
    }
  }

  Future<void> _fetchMoreProducts() async {
    if (!_isLoading && _hasMoreData) {
      setState(() {
        _isLoading = true;
        _currentPage++;
      });
      await _fetchProducts();
    }
  }

  void _clearFilters() {
    setState(() {
      _selectedCategory = null;
      _selectedPriceRange = null;
      _selectedAvailability = null;
      _products.clear();
      _currentPage = 1;
    });
    _fetchProducts();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: Builder(
          builder: (context) {
            return GestureDetector(
              onTap: () => Scaffold.of(context).openDrawer(),
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: SvgPicture.asset(
                  'assets/svg/menu.svg',
                ),
              ),
            );
          },
        ),
        actions: [
          GestureDetector(
            onTap: () => Get.to(CartScreen()),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Stack(
                children: [
                  Icon(Icons.shopping_cart, size: 30,),
                  // Cart count display
                  Positioned(
                    right: 0,
                    child: Obx(() =>
                    cartController.cartCount.value > 0
                        ? Container(
                      padding: EdgeInsets.all(4),
                      decoration: BoxDecoration(
                        color: Colors.red,
                        shape: BoxShape.circle,
                      ),
                      child: Text(
                        '${cartController.cartCount.value}',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                      ),
                    )
                        : SizedBox.shrink()),
                  ),
                ],
              ),
            ),
          ),
        ],
        title: const Text(
          "Product Catalogue",
        ),
      ),
      drawer: const MyDrawer(),
      body: Stack(
        fit: StackFit.expand,
        children: [
          Image.asset(
            'assets/images/image_1.png',
            fit: BoxFit.cover,
          ),
          SafeArea(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  SizedBox(height: Get.height * 0.02),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 18.0),
                    child: TextField(
                      decoration: InputDecoration(
                        hintText: "Search Products",
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(15),
                        ),
                        filled: true,
                        fillColor: Colors.white.withOpacity(0.9),
                      ),
                    ),
                  ),
                  SizedBox(height: Get.height * 0.02),
                  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: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "Filters",
                                style: GoogleFonts.poppins(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16,
                                ),
                              ),
                              TextButton(
                                onPressed: _clearFilters,
                                child: Text(
                                  "Clear Filters",
                                  style: GoogleFonts.poppins(
                                    color: Colors.red,
                                    fontSize: 14,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: Get.height * 0.05,
                            child: ListView.builder(
                              shrinkWrap: true,
                              scrollDirection: Axis.horizontal,
                              itemCount: 3,
                              itemBuilder: (context, index) =>
                                  _buildFilterDropdown(index),
                            ),
                          ),
                          SizedBox(
                            height: Get.height * 0.6,
                            child: ListView.builder(
                              controller: _scrollController,
                              padding: EdgeInsets.zero,
                              itemCount: _products.length +
                                  (_isLoading ? 1 : 0),
                              itemBuilder: (context, index) {
                                if (index >= _products.length) {
                                  print("Product length $_products");
                                  return const Center(
                                      child: CircularProgressIndicator());
                                }
                                return Padding(
                                  padding: const EdgeInsets.symmetric(
                                      vertical: 8),
                                  child: ProductCard(
                                    productModel: _products[index],
                                    // Use ProductModel here
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  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",
        );
      // case 1:
      //   return _buildStyledDropdown(
      //     value: _selectedPriceRange,
      //     onChanged: (value) {
      //       setState(() {
      //         _selectedPriceRange = value;
      //       });
      //     },
      //     items: [
      //       const DropdownMenuItem<String>(
      //         value: "Under ₹50",
      //         child: Text("Under ₹50"),
      //       ),
      //       const DropdownMenuItem<String>(
      //         value: "₹50 - ₹100",
      //         child: Text("₹50 - ₹100"),
      //       ),
      //       const DropdownMenuItem<String>(
      //         value: "Above ₹100",
      //         child: Text("Above ₹100"),
      //       ),
      //     ],
      //     hint: "Price Range",
      //   );
      // case 2:
      //   return _buildStyledDropdown(
      //     value: _selectedAvailability,
      //     onChanged: (value) {
      //       setState(() {
      //         _selectedAvailability = value;
      //       });
      //     },
      //     items: [
      //       const DropdownMenuItem<String>(
      //         value: "In Stock",
      //         child: Text("In Stock"),
      //       ),
      //       const DropdownMenuItem<String>(
      //         value: "Out of Stock",
      //         child: Text("Out of Stock"),
      //       ),
      //     ],
      //     hint: "Availability",
      //   );
      default:
        return const SizedBox();
    }
  }

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

}
