import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../widgets/my_drawer.dart';
import '../../widgets/product_card.dart';
import '../../controller/product_service.dart';

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();
  List<Map<String, dynamic>> _products = [];
  List<Map<String, dynamic>> _categories = [];

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

  String? _selectedCategory; // Default to null to handle 'All' explicitly
  String? _selectedPriceRange;
  String? _selectedAvailability;

  @override
  void initState() {
    super.initState();
    _fetchCategories(); // Fetch categories first to set initial filter
    _fetchProducts(); // Fetch products after setting initial filters
    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent &&
          !_isLoading &&
          _hasMoreData) {
        _fetchMoreProducts();
      }
    });
  }

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

    // Adjust the category parameter based on the selected category
    final category = _selectedCategory == 'All' ? null : _selectedCategory;

    final products = await _productService.getProduct(_currentPage, category: category);
    setState(() {
      if (products != null) {
        _products.addAll(products);
        _hasMoreData = products.isNotEmpty;
      }
      _isLoading = false;
    });
  }

  Future<void> _fetchCategories() async {
    final categories = await _productService.getCategory();
    if (categories != null) {
      setState(() {
        _categories = categories;
        // Add "All" option
        _categories.insert(1, {'categoryName': 'All'});
        _selectedCategory = 'All'; // Set initial selected category to "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.back(),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: SvgPicture.asset(
                'assets/svg/back_arrow.svg',
              ),
            ),
          ),
        ],
        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),
                  // Search Bar
                  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) => Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 4),
                                child: _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],
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFilterDropdown(int index) {
    switch (index) {
      case 0:
        return DropdownButton<String>(
          value: _selectedCategory,
          hint: const Text("Category"),
          onChanged: (value) {
            if (value != null) {
              _onCategoryChanged(value);
            }
          },
          items: _categories.map<DropdownMenuItem<String>>((category) {
            return DropdownMenuItem<String>(
              value: category['categoryName'],
              child: Text(category['categoryName']),
            );
          }).toList(),
        );
      case 1:
        return DropdownButton<String>(
          value: _selectedPriceRange,
          hint: const Text("Price Range"),
          onChanged: (value) {
            setState(() {
              _selectedPriceRange = value;
            });
          },
          items: <String>['\$0-\$50', '\$51-\$100', '\$101-\$150']
              .map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value),
            );
          }).toList(),
        );
      case 2:
        return DropdownButton<String>(
          value: _selectedAvailability,
          hint: const Text("Availability"),
          onChanged: (value) {
            setState(() {
              _selectedAvailability = value;
            });
          },
          items: <String>['In Stock', 'Out of Stock']
              .map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value),
            );
          }).toList(),
        );
      default:
        return Container();
    }
  }
}
