

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

class ProductCard extends StatefulWidget {
  final ProductItem item;
  final VoidCallback? onAddTap;
  final VoidCallback? onIncrementTap;
  final VoidCallback? onDecrementTap;
  final int quantity; // 0 = show "Add", >0 = show stepper

  const ProductCard({
    super.key,
    required this.item,
    this.onAddTap,
    this.onIncrementTap,
    this.onDecrementTap,
    this.quantity = 0,
  });

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

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

  @override
  void initState() {
    super.initState();
    _isFav = widget.item.isFavorite;
  }

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

    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: [

              // Product image
              ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(20)),
                child: CachedNetworkImage(
                  imageUrl: item.image,
                  height: 100,
                  width: double.infinity,
                  fit: BoxFit.cover,
                  placeholder: (_, __) => const SizedBox.shrink(),
                  errorWidget: (context, url, error) => Container(
                    height: 140,
                    color: const Color(0xFFF3F0FF),
                    child: Image.network('https://i0.wp.com/www.chitrasfoodbook.com/wp-content/uploads/2014/08/vegetables-for-salad.jpg?w=1200&ssl=1'),
                  ),
                ),
              ),

              // 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 button — top right
              Positioned(
                top: 8,
                right: 8,
                child: FavButton(
                  size: 32,
                  initialValue: _isFav,
                  onChanged: (val) => setState(() => _isFav = val),
                ),
              ),

              // Add / Stepper button — bottom right ON image
              Positioned(
                bottom: 10,
                right: 10,
                child: AnimatedSwitcher(
                  duration: const Duration(milliseconds: 250),
                  switchInCurve: Curves.easeOutBack,
                  switchOutCurve: Curves.easeIn,
                  transitionBuilder: (child, animation) {
                    return ScaleTransition(
                      scale: animation,
                      child: FadeTransition(
                        opacity: animation,
                        child: child,
                      ),
                    );
                  },
                  child: widget.quantity <= 0
                      ? GestureDetector(
                    key: const ValueKey('add_button'), // important!
                    onTap: widget.onAddTap,
                    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,
                      ),
                    ),
                  )
                      : Container(
                    key: const ValueKey('counter_row'), // important!
                    height: 34,
                    padding: const EdgeInsets.symmetric(horizontal: 4),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.12),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        GestureDetector(
                          onTap: widget.onDecrementTap,
                          child: const Icon(
                            Icons.remove_rounded,
                            color: Color(0xFF662582),
                            size: 18,
                          ),
                        ),
                        const SizedBox(width: 6),
                        Text(
                          '${widget.quantity}',
                          style: const TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w700,
                            color: Color(0xFF1A1A1A),
                          ),
                        ),
                        const SizedBox(width: 6),
                        GestureDetector(
                          onTap: widget.onIncrementTap,
                          child: const Icon(
                            Icons.add_rounded,
                            color: Color(0xFF662582),
                            size: 18,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),

            ],
          ),

          // ── 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),

                // Product 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
                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 — no button here anymore
                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,
                    //     ),
                    //   ),
                  ],
                ),

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