import 'package:autos/core/theme/app_typography.dart';
import 'package:autos/core/widgets/hamburger_button.dart';
import 'package:autos/core/widgets/side_menu.dart';
import 'package:autos/presentation/providers/products_provider.dart';
import 'package:autos/presentation/providers/user_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class ProductsScreen extends ConsumerStatefulWidget {
  const ProductsScreen({super.key});

  @override
  ConsumerState<ProductsScreen> createState() => _ProductsScreenState();
}

class _ProductsScreenState extends ConsumerState<ProductsScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  String selected = 'products';

  bool _hasFetched = false; // ✅ prevents multiple API calls

  // Filter state
  String _searchText = '';
  bool _inStockOnly = false;

  @override
  void initState() {
    super.initState();

    /// ✅ Wait for widget + provider to be fully ready
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadUserFromProvider();
    });
  }

  /// ✅ LOAD USER FROM RIVERPOD (NOT SECURE STORAGE)
  void _loadUserFromProvider() {
    final userState = ref.read(userProvider);
    final user = userState.value;

    if (user == null || user.id == null || user.id!.isEmpty) {
      debugPrint("❌ USER NOT FOUND IN PROVIDER");
      return;
    }

    if (_hasFetched) return; // ✅ prevent duplicate API calls
    _hasFetched = true;

    debugPrint(" USER FROM PROVIDER ID: ${user.id}");

    ref.read(productProvider.notifier).getProducts(user.id!);
  }

  /// Filter products based on search text and stock
  List productsFilter(List products) {
    return products.where((product) {
      final matchesSearch =
          _searchText.isEmpty ||
          product.name.toLowerCase().contains(_searchText.toLowerCase());
      final matchesStock = !_inStockOnly || (product.inStock ?? true);
      return matchesSearch && matchesStock;
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    final productsState = ref.watch(productProvider);
    final double topPadding = MediaQuery.of(context).padding.top + 16;

    return Scaffold(
      key: _scaffoldKey,
      drawer: SideMenu(
        selected: selected,
        onItemSelected: (key) {
          setState(() => selected = key);
        },
      ),
      body: Stack(
        children: [
          /// ✅ Page Title
          Positioned(
            top: topPadding,
            left: 0,
            right: 0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "Brand Products",
                  style: AppTypo.h2.copyWith(fontWeight: FontWeight.w700),
                ),
              ],
            ),
          ),

          /// Main Content
          SingleChildScrollView(
            physics: const BouncingScrollPhysics(),
            padding: EdgeInsets.fromLTRB(16, topPadding + 55, 16, 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                /// ✅ SEARCH + FILTER + COUNT ROW (always visible)
                Row(
                  children: [
                    // Search bar
                    Expanded(
                      child: TextField(
                        onChanged: (value) {
                          setState(() => _searchText = value);
                        },
                        decoration: InputDecoration(
                          hintText: "Search products",
                          prefixIcon: const Icon(Icons.search),
                          contentPadding: const EdgeInsets.symmetric(
                            vertical: 0,
                            horizontal: 16,
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                            borderSide: const BorderSide(color: Colors.grey),
                          ),
                          filled: true,
                          fillColor: Colors.white,
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),

                    // In Stock Only button
                    ElevatedButton(
                      onPressed: () {
                        setState(() => _inStockOnly = !_inStockOnly);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _inStockOnly
                            ? Colors.green
                            : Colors.grey,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: Text(
                        "In Stock",
                        style: const TextStyle(fontSize: 12),
                      ),
                    ),
                    const SizedBox(width: 12),

                    // Count button
                    productsState.when(
                      data: (products) {
                        final filteredProducts = productsFilter(products);
                        return ElevatedButton(
                          onPressed: () {},
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.deepPurple,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                          child: Text(
                            "${filteredProducts.length} products",
                            style: const TextStyle(fontSize: 12),
                          ),
                        );
                      },
                      loading: () => const SizedBox(),
                      error: (_, __) => const SizedBox(),
                    ),
                  ],
                ),
                const SizedBox(height: 16),

                /// ✅ PRODUCTS GRID / LOADING / ERROR
                productsState.when(
                  /// ✅ LOADING
                  loading: () => const Center(
                    child: Padding(
                      padding: EdgeInsets.only(top: 120),
                      child: CircularProgressIndicator(),
                    ),
                  ),

                  /// ✅ ERROR
                  error: (e, _) => Center(
                    child: Padding(
                      padding: const EdgeInsets.only(top: 120),
                      child: Text(
                        (() {
                          final raw = e.toString();
                          // Extract backend message if exists
                          final match = RegExp(
                            r'message[: ]+([^}]+)',
                          ).firstMatch(raw);
                          if (match != null) return match.group(1)!.trim();
                          return raw.replaceFirst(
                            RegExp(r'^Exception:\s*'),
                            '',
                          );
                        })(),
                        textAlign: TextAlign.center,
                        style: const TextStyle(color: Colors.red),
                      ),
                    ),
                  ),

                  /// ✅ SUCCESS
                  data: (products) {
                    if (products.isEmpty) {
                      return const Center(
                        child: Padding(
                          padding: EdgeInsets.only(top: 120),
                          child: Text("No products found"),
                        ),
                      );
                    }

                    final filteredProducts = productsFilter(products);

                    return GridView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: filteredProducts.length,
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            crossAxisSpacing: 12,
                            mainAxisSpacing: 12,
                            childAspectRatio: 0.68,
                          ),
                      itemBuilder: (context, index) {
                        final product = filteredProducts[index];

                        return Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(14),
                            boxShadow: [
                              BoxShadow(
                                blurRadius: 10,
                                color: Colors.black.withOpacity(0.05),
                                offset: const Offset(0, 4),
                              ),
                            ],
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              /// ✅ Product Image
                              Expanded(
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(10),
                                  child: Image.network(
                                    product.image,
                                    width: double.infinity,
                                    fit: BoxFit.cover,
                                    errorBuilder: (_, __, ___) =>
                                        const Icon(Icons.image_not_supported),
                                  ),
                                ),
                              ),
                              const SizedBox(height: 10),

                              /// ✅ Product Name
                              Text(
                                product.name,
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: const TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                              const SizedBox(height: 6),

                              /// ✅ Price
                              Text(
                                "₹ ${product.price}",
                                style: const TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.green,
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    );
                  },
                ),
              ],
            ),
          ),

          /// ✅ Hamburger Button
          HamburgerButton(scaffoldKey: _scaffoldKey),
        ],
      ),
    );
  }
}
