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/domain/entities/import_product.dart';
import 'package:autos/presentation/providers/imports_provider.dart';
import 'package:autos/presentation/screens/imports/imports_header.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

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

  @override
  ConsumerState<ImportsScreen> createState() => _ImportsScreenState();
}

class _ImportsScreenState extends ConsumerState<ImportsScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  String selected = 'imports';

  /// ✅ Selection & Filters
  Set<String> selectedProducts = {};
  bool inStockOnly = false;
  String searchQuery = '';

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

    /// ✅ Load API data on screen open
    Future.microtask(() {
      ref.read(importsProvider.notifier).loadProducts();
    });
  }

  /// ✅ FILTER LOGIC
  List<ImportProductEntity> filterProducts(List<ImportProductEntity> products) {
    return products.where((product) {
      final matchesSearch = product.name.toLowerCase().contains(
        searchQuery.toLowerCase(),
      );

      final matchesStock =
          !inStockOnly || product.inventory > 0; // ✅ REAL STOCK CHECK

      return matchesSearch && matchesStock;
    }).toList();
  }

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

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

          /// ✅ MAIN CONTENT
          SingleChildScrollView(
            padding: EdgeInsets.fromLTRB(16, topPadding + 70, 16, 20),
            child: Column(
              children: [
                ImportsHeader(
                  visibleCount: 47,
                  pageSize: 48,
                  totalCount: 373,
                  selectedCount: selectedProducts.length,

                  onSearch: (value) {
                    debugPrint("Search: $value");
                  },

                  onStockToggle: (value) {
                    debugPrint("Stock Only: $value");
                  },

                  onCategoryChange: (value) {
                    debugPrint("Category: $value");
                  },

                  onSubcategoryChange: (value) {
                    debugPrint("Subcategory: $value");
                  },

                  onOfferStatusChange: (value) {
                    debugPrint("Offer Status: $value");
                  },

                  onPriceChange: (value) {
                    debugPrint("Price Floor: $value");
                  },
                ),

                const SizedBox(height: 10),

                /// ✅ PRODUCT LIST FROM API
                productsAsync.when(
                  loading: () => const Padding(
                    padding: EdgeInsets.only(top: 40),
                    child: CircularProgressIndicator(),
                  ),
                  error: (e, _) => Padding(
                    padding: const EdgeInsets.all(20),
                    child: Text("❌ Error: $e"),
                  ),
                  data: (products) {
                    final filtered = filterProducts(products);

                    return Column(
                      children: [
                        ListView.builder(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: filtered.length,
                          itemBuilder: (context, index) {
                            final product = filtered[index];
                            final isSelected = selectedProducts.contains(
                              product.id,
                            );

                            return ImportProductCard(
                              product: product,
                              selected: isSelected,
                              onTap: () {
                                setState(() {
                                  if (isSelected) {
                                    selectedProducts.remove(product.id);
                                  } else {
                                    selectedProducts.add(product.id);
                                  }
                                });
                              },
                            );
                          },
                        ),

                        const SizedBox(height: 20),

                        /// ✅ SUBMIT BUTTON
                        SizedBox(
                          width: double.infinity,
                          child: ElevatedButton(
                            onPressed: selectedProducts.isEmpty
                                ? null
                                : () {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(
                                        content: Text(
                                          'Submitted ${selectedProducts.length} products',
                                        ),
                                      ),
                                    );
                                  },
                            child: Text(
                              'Submit (${selectedProducts.length}) selected items',
                            ),
                          ),
                        ),
                      ],
                    );
                  },
                ),
              ],
            ),
          ),

          /// ✅ HAMBURGER BUTTON
          HamburgerButton(scaffoldKey: _scaffoldKey),
        ],
      ),
    );
  }
}

class ImportProductCard extends StatelessWidget {
  final ImportProductEntity product;
  final bool selected;
  final VoidCallback onTap;

  const ImportProductCard({
    super.key,
    required this.product,
    required this.selected,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(14),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            /// ✅ TOP ROW
            Row(
              children: [
                Checkbox(value: selected, onChanged: (_) => onTap()),
                const Text("Select"),
                const Spacer(),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 10,
                    vertical: 4,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.blue.withOpacity(.1),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Text("Will list: ${product.inventory}"),
                ),
              ],
            ),

            /// ✅ IMAGE
            ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: Image.network(
                product.image,
                height: 160,
                width: double.infinity,
                fit: BoxFit.contain,
                errorBuilder: (_, __, ___) =>
                    const Icon(Icons.image_not_supported, size: 80),
              ),
            ),

            const SizedBox(height: 10),

            /// ✅ TITLE
            Text(
              product.name,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
            ),

            const SizedBox(height: 6),

            /// ✅ META INFO
            Text("Part #: ${product.partNumber}"),
            Text("${product.category} > ${product.subcategory}"),

            const SizedBox(height: 6),

            /// ✅ PRICE + INVENTORY
            Text(
              "Price: \$${product.price}",
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
            Text("Inventory: ${product.inventory}"),

            const SizedBox(height: 10),

            /// ✅ DESCRIPTION PREVIEW
            Text(product.name, maxLines: 2, overflow: TextOverflow.ellipsis),

            const SizedBox(height: 8),

            /// ✅ STATUS TAGS
            Row(
              children: [
                _statusChip("published", product.offerStatus == "published"),
                const SizedBox(width: 8),
                _statusChip("Listing", true),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _statusChip(String label, bool active) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: active ? Colors.green.withOpacity(.15) : Colors.grey[200],
        borderRadius: BorderRadius.circular(20),
      ),
      child: Text(
        label,
        style: TextStyle(
          color: active ? Colors.green : Colors.grey[600],
          fontWeight: FontWeight.w600,
        ),
      ),
    );
  }
}
