import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:nearledaily/view/product/product_details.dart';
import 'package:nearledaily/view/product/refill_home_screen.dart';
import 'package:wheel_chooser/wheel_chooser.dart';

import '../../widgets/fav_button.dart';

// ─────────────────────────────────────────────
// MODEL
// ─────────────────────────────────────────────

class ProductItem {
  final String name;
  final String category;
  final String price;
  final String originalPrice;
  final String imageUrl;
  final Color bgColor;
  final double rating;
  final int reviewCount;
  final String tag;

  ProductItem({
    required this.name,
    required this.category,
    required this.price,
    required this.originalPrice,
    required this.imageUrl,
    required this.bgColor,
    required this.rating,
    required this.reviewCount,
    required this.tag,
  });
}

// ─────────────────────────────────────────────
// SAMPLE DATA
// ─────────────────────────────────────────────

final allProducts = [
  ProductItem(
    name: 'Margherita Pizza',
    category: 'Dominos · 20 min',
    price: '₹149',
    originalPrice: '₹199',
    imageUrl:
    'https://images.unsplash.com/photo-1513104890138-7c749659a591?w=500',
    bgColor: const Color(0xFFFFF3E0),
    rating: 4.6,
    reviewCount: 512,
    tag: 'Food',
  ),

  ProductItem(
    name: 'Fresh Veggie Basket',
    category: 'BigBasket · 45 min',
    price: '₹299',
    originalPrice: '₹420',
    imageUrl:
    'https://images.unsplash.com/photo-1542838132-92c53300491e?w=500',
    bgColor: const Color(0xFFE8F5E9),
    rating: 4.5,
    reviewCount: 180,
    tag: 'Grocery',
  ),
  ProductItem(
    name: 'Margherita Pizza',
    category: 'Dominos · 20 min',
    price: '₹149',
    originalPrice: '₹199',
    imageUrl:
    'https://images.unsplash.com/photo-1513104890138-7c749659a591?w=500',
    bgColor: const Color(0xFFFFF3E0),
    rating: 4.6,
    reviewCount: 512,
    tag: 'Food',
  ),

  ProductItem(
    name: 'Chicken Biryani',
    category: 'HotPot · 30 min',
    price: '₹189',
    originalPrice: '₹240',
    imageUrl:
    'https://images.unsplash.com/photo-1631515243349-e0cb75fb8d3a?w=500',
    bgColor: const Color(0xFFFBE9E7),
    rating: 4.8,
    reviewCount: 320,
    tag: 'Food',
  ),
  ProductItem(
    name: 'Margherita Pizza',
    category: 'Dominos · 20 min',
    price: '₹149',
    originalPrice: '₹199',
    imageUrl:
    'https://images.unsplash.com/photo-1513104890138-7c749659a591?w=500',
    bgColor: const Color(0xFFFFF3E0),
    rating: 4.6,
    reviewCount: 512,
    tag: 'Food',
  ),
  ProductItem(
    name: 'Birthday Cake',
    category: 'CakeZone · 60 min',
    price: '₹549',
    originalPrice: '₹699',
    imageUrl:
    'https://images.unsplash.com/photo-1578985545062-69928b1d9587?w=500',
    bgColor: const Color(0xFFFCE4EC),
    rating: 4.9,
    reviewCount: 94,
    tag: 'Bakery',
  ),
  ProductItem(
    name: 'Margherita Pizza',
    category: 'Dominos · 20 min',
    price: '₹149',
    originalPrice: '₹199',
    imageUrl:
    'https://images.unsplash.com/photo-1513104890138-7c749659a591?w=500',
    bgColor: const Color(0xFFFFF3E0),
    rating: 4.6,
    reviewCount: 512,
    tag: 'Food',
  ),
];

// ─────────────────────────────────────────────
// FILTER CHIPS DATA
// ─────────────────────────────────────────────

const filterTabs = ['All', 'Food', 'Grocery', 'Bakery', 'Drinks'];

// ─────────────────────────────────────────────
// PRODUCTS PAGE
// ─────────────────────────────────────────────

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

  @override
  State<ProductsList> createState() => _ProductsListState();
}

class _ProductsListState extends State<ProductsList> {
  String _selectedFilter = 'All';
  String _sortBy = 'Popular';

  List<ProductItem> get _filtered => _selectedFilter == 'All'
      ? allProducts
      : allProducts.where((p) => p.tag == _selectedFilter).toList();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF7F7FA),
      body: CustomScrollView(
        slivers: [

          // ── App Bar ──
          SliverAppBar(
            backgroundColor: Colors.white,
            elevation: 0,
            pinned: true,
            title: const Text(
              'Products',
              style: TextStyle(
                color: Color(0xFF1A1A1A),
                fontSize: 18,
                fontWeight: FontWeight.w700,
              ),
            ),
            centerTitle: false,
            leading: const BackButton(color: Color(0xFF1A1A1A)),
            actions: [
              IconButton(
                icon: const Icon(Icons.search_rounded,
                    color: Color(0xFF1A1A1A)),
                onPressed: () {

                  Navigator.push(context, MaterialPageRoute(builder: (context) => const AutoRefillDemo()));
                },
              ),
              IconButton(
                icon: const Icon(Icons.tune_rounded,
                    color: Color(0xFF1A1A1A)),
                onPressed: () => _showSortSheet(context),
              ),
            ],
            bottom: PreferredSize(
              preferredSize: const Size.fromHeight(1),
              child: Container(
                height: 1,
                color: const Color(0xFFEEEEEE),
              ),
            ),
          ),

          // ── Filter chips ──
          SliverPersistentHeader(
            pinned: true,
            delegate: _FilterHeaderDelegate(
              selectedFilter: _selectedFilter,
              sortBy: _sortBy,
              onFilterChanged: (f) => setState(() => _selectedFilter = f),
              onSortTap: () => _showSortSheet(context),
            ),
          ),




          // ── Product grid ──
          SliverPadding(
            padding: const EdgeInsets.fromLTRB(16, 12, 16, 24),
            sliver: SliverGrid(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                crossAxisSpacing: 12,
                mainAxisSpacing: 12,
                childAspectRatio: 0.72,
              ),
              delegate: SliverChildBuilderDelegate(
                    (context, index) => _ProductCard(item: _filtered[index]),
                childCount: _filtered.length,
              ),
            ),
          ),

        ],
      ),
    );
  }

  void _showSortSheet(BuildContext context) {
    final options = ['Popular', 'Price: Low to High', 'Price: High to Low', 'Rating', 'Discount'];
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
      ),
      builder: (_) => Padding(
        padding: const EdgeInsets.fromLTRB(20, 16, 20, 32),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Center(
              child: Container(
                width: 36,
                height: 4,
                decoration: BoxDecoration(
                  color: const Color(0xFFE0E0E0),
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
            ),
            const SizedBox(height: 16),
            const Text(
              'Sort by',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w700,
                color: Color(0xFF1A1A1A),
              ),
            ),
            const SizedBox(height: 12),
            ...options.map((opt) => InkWell(
              onTap: () {
                setState(() => _sortBy = opt);
                Navigator.pop(context);
              },
              borderRadius: BorderRadius.circular(12),
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 12),
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        opt,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: _sortBy == opt
                              ? FontWeight.w700
                              : FontWeight.w400,
                          color: _sortBy == opt
                              ? const Color(0xFF7C3AED)
                              : const Color(0xFF1A1A1A),
                        ),
                      ),
                    ),
                    if (_sortBy == opt)
                      const Icon(Icons.check_circle_rounded,
                          color: Color(0xFF7C3AED), size: 20),
                  ],
                ),
              ),
            )),
          ],
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────
// STICKY FILTER HEADER DELEGATE
// ─────────────────────────────────────────────

class _FilterHeaderDelegate extends SliverPersistentHeaderDelegate {
  final String selectedFilter;
  final String sortBy;
  final ValueChanged<String> onFilterChanged;
  final VoidCallback onSortTap;

  _FilterHeaderDelegate({
    required this.selectedFilter,
    required this.sortBy,
    required this.onFilterChanged,
    required this.onSortTap,
  });

  @override
  double get minExtent => 56;
  @override
  double get maxExtent => 56;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          Expanded(
            child: ListView.separated(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
              scrollDirection: Axis.horizontal,
              itemCount: filterTabs.length + 1, // +1 for sort chip
              separatorBuilder: (_, __) => const SizedBox(width: 8),
              itemBuilder: (context, index) {
                // Last item = Sort chip
                if (index == filterTabs.length) {
                  return GestureDetector(
                    onTap: onSortTap,
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 14, vertical: 6),
                      decoration: BoxDecoration(
                        color: const Color(0xFFF3F0FF),
                        borderRadius: BorderRadius.circular(20),
                        border: Border.all(
                            color: const Color(0xFFD4C5FF), width: 1),
                      ),
                      child: Row(
                        children: [
                          const Icon(Icons.swap_vert_rounded,
                              size: 15, color: Color(0xFF662582)),
                          const SizedBox(width: 4),
                          Text(
                            sortBy == 'Popular' ? 'Sort' : sortBy,
                            style: const TextStyle(
                              fontSize: 12.5,
                              fontWeight: FontWeight.w600,
                              color: Color(0xFF662582),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                }

                final tab = filterTabs[index];
                final isSelected = selectedFilter == tab;

                return GestureDetector(
                  onTap: () => onFilterChanged(tab),
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 200),
                    padding: const EdgeInsets.symmetric(
                        horizontal: 16, vertical: 6),
                    decoration: BoxDecoration(
                      color: isSelected
                          ? const Color(0xFF662582)
                          : Colors.white,
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(
                        color: isSelected
                            ? const Color(0xFF662582)
                            : const Color(0xFFE0E0E0),
                        width: 1,
                      ),
                    ),
                    child: Text(
                      tab,
                      style: TextStyle(
                        fontSize: 12.5,
                        fontWeight: FontWeight.w600,
                        color: isSelected
                            ? Colors.white
                            : const Color(0xFF757575),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
          Container(height: 1, color: const Color(0xFFEEEEEE)),
        ],
      ),
    );
  }

  @override
  bool shouldRebuild(_FilterHeaderDelegate old) =>
      old.selectedFilter != selectedFilter || old.sortBy != sortBy;
}

// ─────────────────────────────────────────────
// PRODUCT CARD
// ─────────────────────────────────────────────

class _ProductCard extends StatefulWidget {
  final ProductItem item;
  const _ProductCard({required this.item});

  @override
  State<_ProductCard> createState() => _ProductCardState();
}

class _ProductCardState extends State<_ProductCard> {
  bool _isFav = false;


  @override
  Widget build(BuildContext context) {
    final item = widget.item;
    int selectedIndex = 2;

    final original = double.tryParse(
        item.originalPrice.replaceAll(RegExp(r'[^\d.]'), '')) ??
        0;
    final current =
        double.tryParse(item.price.replaceAll(RegExp(r'[^\d.]'), '')) ?? 0;
    final discount =
    original > 0 ? ((original - current) / original * 100).round() : 0;

    return Container(
      decoration: BoxDecoration(

        borderRadius: BorderRadius.circular(20),

      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [

          // ── Image area ──
          Stack(
            children: [

              // Image or emoji fallback
              GestureDetector(
                onTap: () => showProductSheet(context, item),

                child: SizedBox(
                  height: 140,
                  width: double.infinity,
                  child: ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(20)),
                    child: CachedNetworkImage(
                      imageUrl: item.imageUrl,
                      fit: BoxFit.cover,
                      placeholder: (context, url) => const Center(
                        child: CircularProgressIndicator(),
                      ),
                      errorWidget: (context, url, error) => _fallback(item),
                    ),
                  ),
                ),
              ),

              // Discount badge — top left
              if (discount > 0)
                Positioned(
                  top: 10,
                  left: 10,
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: const Color(0xFF662582),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Text(
                      '$discount% OFF',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 10,
                        fontWeight: FontWeight.w700,
                        letterSpacing: 0.3,
                      ),
                    ),
                  ),
                ),

              // Favourite — top right
              Positioned(
                top: 8,
                right: 8,
                child: FavButton(
                  size: 32,
                  initialValue: _isFav,
                  onChanged: (val) => setState(() => _isFav = val),
                ),
              ),

              // Add button — bottom right ON image
              Positioned(
                bottom: 10,
                right: 10,
                child: GestureDetector(

                  onTap: () {
                    showModalBottomSheet(

                      context: context,
                      shape: const RoundedRectangleBorder(
                        borderRadius: BorderRadius.vertical(
                          top: Radius.circular(24),
                        ),
                      ),
                      builder: (context) {
                        return StatefulBuilder(
                          builder: (context, setModalState) {
                            return Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: const BorderRadius.vertical(
                                  top: Radius.circular(24),
                                ),
                              ),
                              height: 420,
                              padding: const EdgeInsets.symmetric(vertical: 20),
                              child: Column(
                                children: [
                                  Container(
                                    width: 50,
                                    height: 5,
                                    decoration: BoxDecoration(
                                      color: Colors.grey.shade300,
                                      borderRadius: BorderRadius.circular(100),
                                    ),
                                  ),

                                  const SizedBox(height: 20),

                                  const Text(
                                    "Choose Variant",
                                    style: TextStyle(
                                      fontSize: 22,
                                      fontWeight: FontWeight.bold,
                                      color: Color(0xFF662582),
                                    ),
                                  ),

                                  const SizedBox(height: 3),

                                  Text(
                                    "Scroll to select your size",
                                    style: TextStyle(
                                      color: Colors.grey.shade600,
                                      fontSize: 13,
                                    ),
                                  ),

                                  const SizedBox(height: 20),

                                  Expanded(
                                    child: PageView.builder(
                                      controller: PageController(
                                        viewportFraction: 0.30,
                                        initialPage: selectedIndex,
                                      ),
                                      onPageChanged: (index) {
                                        setModalState(() {
                                          selectedIndex = index;
                                        });
                                      },
                                      itemCount: 5,
                                      itemBuilder: (context, index) {
                                        final items = [
                                          {
                                            "name": "Small",
                                            "price": "₹149",
                                            "image":
                                            "https://images.unsplash.com/photo-1513104890138-7c749659a591?w=500",
                                          },
                                          {
                                            "name": "Medium",
                                            "price": "₹199",
                                            "image":
                                            "https://images.unsplash.com/photo-1565299624946-b28f40a0ae38?w=500",
                                          },
                                          {
                                            "name": "Large",
                                            "price": "₹249",
                                            "image":
                                            "https://images.unsplash.com/photo-1514326640560-7d063ef2aed5?w=500",
                                          },
                                          {
                                            "name": "XL",
                                            "price": "₹299",
                                            "image":
                                            "https://images.unsplash.com/photo-1594007654729-407eedc4be65?w=500",
                                          },
                                          {
                                            "name": "Party",
                                            "price": "₹399",
                                            "image":
                                            "https://images.unsplash.com/photo-1514326640560-7d063ef2aed5?w=500",
                                          },
                                        ];

                                        final isSelected = selectedIndex == index;

                                        return AnimatedContainer(
                                          duration: const Duration(milliseconds: 300),
                                          curve: Curves.easeOut,
                                          transform: Matrix4.identity()
                                            ..scale(isSelected ? 1.15 : 1.15),
                                          child: Column(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            children: [
                                              Stack(
                                                clipBehavior: Clip.none,
                                                alignment: Alignment.center,
                                                children: [
                                                  AnimatedContainer(
                                                    duration: const Duration(milliseconds: 300),
                                                    width: isSelected ? 100 : 85,
                                                    height: isSelected ? 100 : 85,
                                                    decoration: BoxDecoration(
                                                      shape: BoxShape.circle,
                                                      border: Border.all(
                                                        color: isSelected
                                                            ? const Color(0xFF662582)
                                                            : Colors.transparent,
                                                        width: 3,
                                                      ),

                                                    ),
                                                    child: ClipOval(
                                                      child: Image.network(
                                                        items[index]["image"]!,
                                                        fit: BoxFit.fill,

                                                      ),
                                                    ),
                                                  ),


                                                ],
                                              ),

                                              const SizedBox(height: 15),

                                              AnimatedDefaultTextStyle(
                                                duration: const Duration(milliseconds: 300),
                                                style: TextStyle(
                                                  fontSize: isSelected ? 18 : 14,
                                                  fontWeight: FontWeight.bold,
                                                  color: isSelected
                                                      ? Colors.black
                                                      : Colors.grey.shade600,
                                                ),
                                                child: Text(items[index]["name"]!),
                                              ),

                                              const SizedBox(height: 5),

                                              AnimatedDefaultTextStyle(
                                                duration: const Duration(milliseconds: 300),
                                                style: TextStyle(
                                                  color: const Color(0xFF662582),
                                                  fontWeight: FontWeight.w700,
                                                  fontSize: isSelected ? 16 : 12,
                                                ),
                                                child: Text(items[index]["price"]!),
                                              ),

                                              const SizedBox(height: 10),


                                            ],
                                          ),
                                        );
                                      },
                                    ),
                                  ),




                                  const SizedBox(height: 20),

                                  Padding(
                                    padding: const EdgeInsets.symmetric(horizontal: 20),
                                    child: SizedBox(
                                      width: double.infinity,
                                      height: 56,
                                      child: ElevatedButton(
                                        style: ElevatedButton.styleFrom(
                                          backgroundColor: const Color(0xFF662582),
                                          shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(18),
                                          ),
                                        ),
                                        onPressed: () {},
                                        child: const Text(
                                          "Confirm Selection",
                                          style: TextStyle(
                                            fontSize: 16,
                                            fontWeight: FontWeight.w700,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        );
                      },
                    );
                  },
                  child: Container(
                    width: 34,
                    height: 34,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      shape: BoxShape.circle,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.12),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: const Icon(
                      Icons.add_rounded,
                      color: Color(0xFF662582),
                      size: 20,
                    ),
                  ),
                ),
              ),
            ],
          ),

          // ── Info area ──
          Padding(
            padding: const EdgeInsets.fromLTRB(12, 10, 12, 12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [

                // Category
                Text(
                  item.category,
                  style: const TextStyle(
                    fontSize: 10.5,
                    color: Color(0xFF662582),
                    fontWeight: FontWeight.w600,
                    letterSpacing: 0.2,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),

                const SizedBox(height: 3),

                // Name
                Text(
                  item.name,
                  style: const TextStyle(
                    fontSize: 13.5,
                    fontWeight: FontWeight.w700,
                    color: Color(0xFF1A1A1A),
                    height: 1.2,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),

                const SizedBox(height: 6),

                // Rating
                Row(
                  children: [
                    const Icon(Icons.star_rounded,
                        size: 13, color: Color(0xFFFFC107)),
                    const SizedBox(width: 3),
                    Text(
                      '${item.rating}',
                      style: const TextStyle(
                        fontSize: 11,
                        fontWeight: FontWeight.w700,
                        color: Color(0xFF1A1A1A),
                      ),
                    ),
                    const SizedBox(width: 3),
                    Text(
                      '(${item.reviewCount})',
                      style: const TextStyle(
                        fontSize: 10.5,
                        color: Color(0xFF9E9E9E),
                      ),
                    ),
                  ],
                ),

                const SizedBox(height: 8),

                // Price
                Row(
                  children: [
                    Text(
                      item.price,
                      style: const TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w800,
                        color: Color(0xFF1A1A1A),
                      ),
                    ),
                    const SizedBox(width: 6),
                    if (discount > 0)
                      Text(
                        item.originalPrice,
                        style: const TextStyle(
                          fontSize: 11,
                          color: Color(0xFF9E9E9E),
                          decoration: TextDecoration.lineThrough,
                        ),
                      ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _fallback(ProductItem item) {
    return Container(
      height: 140,
      width: double.infinity,
      color: item.bgColor,
      child: const Center(
        child: Icon(
          Icons.image_not_supported,
          size: 40,
          color: Colors.grey,
        ),
      ),
    );
  }
}