import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:nearledaily/view/product/products_list.dart';

// ─── Entry point ───────────────────────────────────────────────────────────────

void showProductSheet(BuildContext context, ProductItem item) {
  showModalBottomSheet(
    context: context,
    isScrollControlled: true,
    backgroundColor: Colors.transparent,
    barrierColor: Colors.black.withOpacity(0.4),
    builder: (_) => _ProductSheet(item: item),
  );
}

// ─── Sheet widget ──────────────────────────────────────────────────────────────

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

  @override
  State<_ProductSheet> createState() => _ProductSheetState();
}

class _ProductSheetState extends State<_ProductSheet> {
  final DraggableScrollableController _drag = DraggableScrollableController();

  static const double _minSize = 0.54;
  static const double _maxSize = 1.0;

  int _qty = 1;
  bool _isFav = false;
  bool _inCart = false;
  double _expansion = 0.0;

  static const Color _purple = Color(0xFF662582);
  static const Color _purpleLight = Color(0xFFF0EBFF);
  static const Color _dark = Color(0xFF111111);
  static const Color _surface = Color(0xFFF8F8F8);
  static const Color _muted = Color(0xFF888888);

  @override
  void initState() {
    super.initState();
    _drag.addListener(_onDrag);
  }

  void _onDrag() {
    if (!_drag.isAttached) return;
    final t = ((_drag.size - _minSize) / (_maxSize - _minSize)).clamp(0.0, 1.0);
    if (t > 0.88) {
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
    } else {
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    }
    setState(() => _expansion = t);
  }

  @override
  void dispose() {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    _drag.removeListener(_onDrag);
    _drag.dispose();
    super.dispose();
  }

  int get _discount {
    final orig = double.tryParse(
        widget.item.originalPrice.replaceAll(RegExp(r'[^\d.]'), '')) ?? 0;
    final cur = double.tryParse(
        widget.item.price.replaceAll(RegExp(r'[^\d.]'), '')) ?? 0;
    return orig > 0 ? ((orig - cur) / orig * 100).round() : 0;
  }

  String get _savedAmount {
    final orig = double.tryParse(
        widget.item.originalPrice.replaceAll(RegExp(r'[^\d.]'), '')) ?? 0;
    final cur = double.tryParse(
        widget.item.price.replaceAll(RegExp(r'[^\d.]'), '')) ?? 0;
    final saved = orig - cur;
    return saved > 0 ? '₹${saved.toStringAsFixed(0)}' : '';
  }

  void _snapToFull() => _drag.animateTo(_maxSize,
      duration: const Duration(milliseconds: 400), curve: Curves.easeOutCubic);

  void _snapToPeek() => _drag.animateTo(_minSize,
      duration: const Duration(milliseconds: 300), curve: Curves.easeOutCubic);

  @override
  Widget build(BuildContext context) {
    final topPad = MediaQuery.of(context).padding.top;
    final botPad = MediaQuery.of(context).padding.bottom;
    final e = _expansion;
    final cornerRadius = lerpDouble(24.0, 0.0, e)!;
    final imageHeight = lerpDouble(300.0, topPad + 340.0, e)!;
    final discount = _discount;
    final saved = _savedAmount;

    return DraggableScrollableSheet(
      controller: _drag,
      initialChildSize: _minSize,
      minChildSize: _minSize,
      maxChildSize: _maxSize,
      snap: true,
      snapSizes: const [_minSize, _maxSize],
      builder: (context, scrollCtrl) {
        return Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius:
            BorderRadius.vertical(top: Radius.circular(cornerRadius)),
          ),
          child: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  controller: scrollCtrl,
                  physics: const ClampingScrollPhysics(),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // ── Hero ──
                      _buildHero(imageHeight, cornerRadius, topPad, e),

                      // ── Drag handle (peek) ──
                      if (e < 0.2)
                        Center(
                          child: Padding(
                            padding: const EdgeInsets.only(top: 12),
                            child: Container(
                              width: 36,
                              height: 4,
                              decoration: BoxDecoration(
                                color: const Color(0xFFDDD8F0),
                                borderRadius: BorderRadius.circular(2),
                              ),
                            ),
                          ),
                        ),

                      // ── Body ──
                      Padding(
                        padding: const EdgeInsets.fromLTRB(20, 20, 20, 0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // Tag chip
                            _tagChip(widget.item.tag),
                            const SizedBox(height: 12),

                            // Product name
                            Text(
                              widget.item.name,
                              style: const TextStyle(
                                fontSize: 22,
                                fontWeight: FontWeight.w700,
                                color: _dark,
                                letterSpacing: -0.4,
                                height: 1.2,
                              ),
                            ),
                            const SizedBox(height: 4),

                            // Category / store
                            Row(
                              children: [
                                Container(
                                  width: 6,
                                  height: 6,
                                  decoration: const BoxDecoration(
                                    color: Color(0xFF4CAF50),
                                    shape: BoxShape.circle,
                                  ),
                                ),
                                const SizedBox(width: 6),
                                Text(
                                  widget.item.category,
                                  style: const TextStyle(
                                    fontSize: 12,
                                    color: _muted,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 18),

                            // Price
                            _buildPriceRow(discount, saved),
                            const SizedBox(height: 6),
                            if (saved.isNotEmpty)
                              Text(
                                'You save $saved · Free delivery on this order',
                                style: const TextStyle(fontSize: 12, color: _muted),
                              ),
                            const SizedBox(height: 18),

                            // Rating
                            _buildRatingRow(),

                            // Swipe hint
                            if (e < 0.12) ...[
                              const SizedBox(height: 20),
                              _swipeHint(),
                            ],

                            // Expanded content
                            if (e > 0.12) ...[
                              const SizedBox(height: 24),

                              // Highlights
                              AnimatedOpacity(
                                duration: const Duration(milliseconds: 300),
                                opacity: e > 0.4 ? 1.0 : 0.0,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    _sectionLabel('Why you\'ll love it'),
                                    const SizedBox(height: 10),
                                    _buildHighlights(),
                                    const SizedBox(height: 24),
                                  ],
                                ),
                              ),

                              // About (derived from name + category)
                              AnimatedOpacity(
                                duration: const Duration(milliseconds: 350),
                                opacity: e > 0.52 ? 1.0 : 0.0,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    _sectionLabel('About'),
                                    const SizedBox(height: 10),
                                    Text(
                                      'A premium quality ${widget.item.name} carefully '
                                          'curated for you. Sourced from trusted partners at '
                                          '${widget.item.category}. Every order is freshness-'
                                          'guaranteed with no compromise on quality.',
                                      style: const TextStyle(
                                        fontSize: 13,
                                        color: Color(0xFF555555),
                                        height: 1.8,
                                      ),
                                    ),
                                    const SizedBox(height: 24),
                                  ],
                                ),
                              ),

                              // Reviews
                              AnimatedOpacity(
                                duration: const Duration(milliseconds: 400),
                                opacity: e > 0.62 ? 1.0 : 0.0,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    _buildDivider(),
                                    const SizedBox(height: 20),
                                    _buildReviewsHeader(),
                                    const SizedBox(height: 12),
                                    _buildReviewCard(
                                      initials: 'PR',
                                      name: 'Priya R.',
                                      date: '2 days ago',
                                      stars: 5,
                                      text:
                                      'Absolutely love it! Super fresh and delivered on time. Will definitely order again.',
                                    ),
                                    const SizedBox(height: 10),
                                    _buildReviewCard(
                                      initials: 'AK',
                                      name: 'Arjun K.',
                                      date: '1 week ago',
                                      stars: 5,
                                      text:
                                      'Great quality and packaging. Exactly as described. Fast delivery too!',
                                    ),
                                    const SizedBox(height: 24),
                                  ],
                                ),
                              ),

                              // Quantity
                              AnimatedOpacity(
                                duration: const Duration(milliseconds: 400),
                                opacity: e > 0.70 ? 1.0 : 0.0,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    _buildDivider(),
                                    const SizedBox(height: 20),
                                    _buildQuantityRow(),
                                    const SizedBox(height: 8),
                                  ],
                                ),
                              ),
                            ],
                          ],
                        ),
                      ),
                      SizedBox(height: botPad + 90),
                    ],
                  ),
                ),
              ),

              // ── CTA bar ──
              _buildCtaBar(botPad),
            ],
          ),
        );
      },
    );
  }

  // ── Hero ────────────────────────────────────────────────────────────────────

  Widget _buildHero(
      double imageHeight, double cornerRadius, double topPad, double e) {
    final item = widget.item;
    final discount = _discount;

    return Stack(
      children: [
        // Product image
        ClipRRect(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(cornerRadius),
            topRight: Radius.circular(cornerRadius),
          ),
          child: Container(
            height: imageHeight,
            width: double.infinity,
            color: item.bgColor,
            child: item.imageUrl.isNotEmpty
                ? CachedNetworkImage(
              imageUrl: item.imageUrl,
              fit: BoxFit.cover,
              placeholder: (_, __) => const Center(
                child: CircularProgressIndicator(
                    strokeWidth: 2, color: _purple),
              ),
              errorWidget: (_, __, ___) => Image.network(
                'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQfoIZCZOkJq4Yg00gVdyXr49xxOJsFjSjABE_SAzOiDQ&s=10',
                fit: BoxFit.cover,
              ),
            )
                : const SizedBox(),
          ),
        ),

        // Back / close button (full screen)
        // Positioned(
        //   top: lerpDouble(-60, topPad + 12, e)!,
        //   left: 14,
        //   child: AnimatedOpacity(
        //     opacity: e > 0.7 ? 1.0 : 0.0,
        //     duration: const Duration(milliseconds: 150),
        //     child: _circleButton(
        //       icon: Icons.arrow_back_ios_new_rounded,
        //       onTap: () {
        //         HapticFeedback.lightImpact();
        //         if (_drag.isAttached && _drag.size > _minSize + 0.05) {
        //           _snapToPeek();
        //         } else {
        //           Navigator.pop(context);
        //         }
        //       },
        //     ),
        //   ),
        // ),

        // Share + search (full screen)


        // Discount badge
        if (discount > 0)
          Positioned(
            bottom: 48,
            left: 16,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
              decoration: BoxDecoration(
                color: _dark,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                '$discount% OFF',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 11,
                  fontWeight: FontWeight.w700,
                  letterSpacing: 0.3,
                ),
              ),
            ),
          ),


      ],
    );
  }

  // ── Tag chip ────────────────────────────────────────────────────────────────

  Widget _tagChip(String label) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      decoration: BoxDecoration(
        color: _purpleLight,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Text(
        label,
        style: const TextStyle(
          fontSize: 11,
          fontWeight: FontWeight.w600,
          color: _purple,
        ),
      ),
    );
  }

  // ── Price ───────────────────────────────────────────────────────────────────

  Widget _buildPriceRow(int discount, String saved) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          widget.item.price,
          style: const TextStyle(
            fontSize: 28,
            fontWeight: FontWeight.w700,
            color: _dark,
            letterSpacing: -0.5,
          ),
        ),
        const SizedBox(width: 10),
        // Text(
        //   widget.item.originalPrice,
        //   style: const TextStyle(
        //     fontSize: 14,
        //     color: Color(0xFFBBBBBB),
        //     decoration: TextDecoration.lineThrough,
        //     decorationColor: Color(0xFFBBBBBB),
        //   ),
        // ),
        if (discount > 0) ...[
          const SizedBox(width: 10),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
            decoration: BoxDecoration(
              color: _dark,
              borderRadius: BorderRadius.circular(6),
            ),
            child: Text(
              '$discount% OFF',
              style: const TextStyle(
                color: Colors.white,
                fontSize: 10,
                fontWeight: FontWeight.w700,
                letterSpacing: 0.3,
              ),
            ),
          ),
        ],
      ],
    );
  }

  // ── Rating ──────────────────────────────────────────────────────────────────

  Widget _buildRatingRow() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 14),
      decoration: const BoxDecoration(
        border: Border(
          top: BorderSide(color: Color(0xFFF0F0F0)),
          bottom: BorderSide(color: Color(0xFFF0F0F0)),
        ),
      ),
      child: Row(
        children: [
          Row(
            children: List.generate(
              5,
                  (i) => Icon(
                i < widget.item.rating.floor()
                    ? Icons.star_rounded
                    : Icons.star_border_rounded,
                size: 16,
                color: Colors.yellow.shade700,
              ),
            ),
          ),
          const SizedBox(width: 8),
          Text(
            widget.item.rating.toStringAsFixed(1),
            style: const TextStyle(
                fontSize: 13, fontWeight: FontWeight.w700, color: _dark),
          ),
          const SizedBox(width: 6),
          // reviewCount is int — convert directly
          Text(
            '· ${widget.item.reviewCount} ratings',
            style: const TextStyle(fontSize: 12, color: _muted),
          ),
          const Spacer(),

        ],
      ),
    );
  }

  // ── Highlights ──────────────────────────────────────────────────────────────

  Widget _buildHighlights() {
    final tiles = [
      _HighlightData(
        icon: Icons.bolt_rounded,
        label: 'Fast\nDelivery',
        sub: '20–45 min',
        iconColor: _purple,
      ),
      _HighlightData(
        icon: Icons.verified_rounded,
        label: 'Quality\nVerified',
        sub: 'Trusted partners',
        iconColor: const Color(0xFF1B5E20),
      ),
      _HighlightData(
        icon: Icons.refresh_rounded,
        label: 'Easy\nReturns',
        sub: 'Hassle-free',
        iconColor: const Color(0xFFB45309),
      ),
      _HighlightData(
        icon: Icons.lock_outline_rounded,
        label: 'Secure\nPay',
        sub: '100% safe',
        iconColor: const Color(0xFF1565C0),
      ),
    ];

    return Row(
      children: List.generate(tiles.length, (index) {
        final t = tiles[index];
        return Expanded(
          child: Container(
            margin: EdgeInsets.only(right: index < tiles.length - 1 ? 8 : 0),
            padding:
            const EdgeInsets.symmetric(vertical: 12, horizontal: 6),
            decoration: BoxDecoration(
              color: _surface,
              borderRadius: BorderRadius.circular(14),
            ),
            child: Column(
              children: [
                Icon(t.icon, color: t.iconColor, size: 20),
                const SizedBox(height: 6),
                Text(
                  t.label,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 10,
                    fontWeight: FontWeight.w700,
                    color: t.iconColor,
                    height: 1.3,
                  ),
                ),
                const SizedBox(height: 3),
                Text(
                  t.sub,
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                      fontSize: 9, color: _muted, height: 1.3),
                ),
              ],
            ),
          ),
        );
      }),
    );
  }

  // ── Reviews ─────────────────────────────────────────────────────────────────

  Widget _buildReviewsHeader() {
    return Row(
      children: [
        const Text(
          'Customer reviews',
          style: TextStyle(
              fontSize: 13, fontWeight: FontWeight.w700, color: _dark),
        ),
        const Spacer(),
        // reviewCount is int

      ],
    );
  }

  Widget _buildReviewCard({
    required String initials,
    required String name,
    required String date,
    required int stars,
    required String text,
  }) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: _surface,
        borderRadius: BorderRadius.circular(14),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              CircleAvatar(
                radius: 15,
                backgroundColor: _purpleLight,
                child: Text(
                  initials,
                  style: const TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w700,
                      color: _purple),
                ),
              ),
              const SizedBox(width: 8),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(name,
                      style: const TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                          color: _dark)),
                  Row(
                    children: List.generate(
                      stars,
                          (_) => const Icon(Icons.star_rounded,
                          size: 11, color: _dark),
                    ),
                  ),
                ],
              ),
              const Spacer(),
              Text(date,
                  style: const TextStyle(fontSize: 11, color: _muted)),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            text,
            style: const TextStyle(
                fontSize: 12, color: Color(0xFF666666), height: 1.6),
          ),
        ],
      ),
    );
  }

  // ── Quantity ─────────────────────────────────────────────────────────────────

  Widget _buildQuantityRow() {
    return Row(
      children: [
        _sectionLabel('Quantity'),
        const SizedBox(width: 16),
        _qtyButton(
          icon: Icons.remove_rounded,
          onTap: () {
            if (_qty > 1) {
              HapticFeedback.lightImpact();
              setState(() => _qty--);
            }
          },
          filled: false,
        ),
        const SizedBox(width: 8),
        AnimatedSwitcher(
          duration: const Duration(milliseconds: 180),
          transitionBuilder: (child, anim) =>
              ScaleTransition(scale: anim, child: child),
          child: Text(
            '$_qty',
            key: ValueKey(_qty),
            style: const TextStyle(
                fontSize: 16, fontWeight: FontWeight.w700, color: _dark),
          ),
        ),
        const SizedBox(width: 8),
        _qtyButton(
          icon: Icons.add_rounded,
          onTap: () {
            HapticFeedback.lightImpact();
            setState(() => _qty++);
          },
          filled: true,
        ),
      ],
    );
  }

  // ── CTA bar ──────────────────────────────────────────────────────────────────

  Widget _buildCtaBar(double botPad) {
    return Container(
      padding: EdgeInsets.fromLTRB(20, 14, 20, botPad + 16),
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: Color(0xFFF0F0F0))),
      ),
      child: Row(
        children: [
          // Wishlist
          GestureDetector(
            onTap: () {
              HapticFeedback.lightImpact();
              setState(() => _isFav = !_isFav);
            },
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 200),
              width: 52,
              height: 52,
              decoration: BoxDecoration(
                color: _isFav ? const Color(0xFFFFF5F5) : Colors.white,
                border: Border.all(
                  color: _isFav
                      ? const Color(0xFFFFD0D0)
                      : const Color(0xFFE8E8E8),
                ),
                borderRadius: BorderRadius.circular(14),
              ),
              child: Icon(
                _isFav
                    ? Icons.favorite_rounded
                    : Icons.favorite_border_rounded,
                color: _isFav ? const Color(0xFFE24B4A) : _dark,
                size: 22,
              ),
            ),
          ),
          const SizedBox(width: 10),

          // Add to bag
          Expanded(
            child: GestureDetector(
              onTap: () {
                HapticFeedback.mediumImpact();
                setState(() => _inCart = true);
                _snapToFull();
              },
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 250),
                height: 52,
                decoration: BoxDecoration(
                  color: _inCart ? const Color(0xFF2E2E2E) : _dark,
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Center(
                  child: Text(
                    _inCart ? 'Added ✓' : 'Add to cart',
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w700,
                      color: Colors.white,
                      letterSpacing: -0.2,
                    ),
                  ),
                ),
              ),
            ),
          ),
          const SizedBox(width: 10),



        ],
      ),
    );
  }

  // ── Swipe hint ───────────────────────────────────────────────────────────────

  Widget _swipeHint() {
    return GestureDetector(
      onTap: _snapToFull,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(vertical: 14),
        decoration: BoxDecoration(
          border: Border.all(color: _purple.withOpacity(0.2)),
          borderRadius: BorderRadius.circular(14),
        ),
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Swipe up for full details',
              style: TextStyle(
                  fontSize: 13, fontWeight: FontWeight.w600, color: _purple),
            ),
            SizedBox(width: 6),
            Icon(Icons.keyboard_arrow_up_rounded, color: _purple, size: 18),
          ],
        ),
      ),
    );
  }

  // ── Helpers ──────────────────────────────────────────────────────────────────

  Widget _buildDivider() =>
      Container(height: 1, color: const Color(0xFFF0F0F0));

  Widget _sectionLabel(String label) => Text(
    label.toUpperCase(),
    style: const TextStyle(
      fontSize: 11,
      fontWeight: FontWeight.w700,
      color: _muted,
      letterSpacing: 1.0,
    ),
  );

  Widget _circleButton({required IconData icon, required VoidCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.85),
          shape: BoxShape.circle,
        ),
        child: Icon(icon, size: 18, color: _dark),
      ),
    );
  }

  Widget _qtyButton(
      {required IconData icon,
        required VoidCallback onTap,
        required bool filled}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          color: filled ? _dark : Colors.white,
          border:
          Border.all(color: filled ? _dark : const Color(0xFFE8E8E8)),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Icon(icon, size: 18, color: filled ? Colors.white : _dark),
      ),
    );
  }
}

// ─── Internal data class ────────────────────────────────────────────────────────

class _HighlightData {
  final IconData icon;
  final String label;
  final String sub;
  final Color iconColor;
  const _HighlightData({
    required this.icon,
    required this.label,
    required this.sub,
    required this.iconColor,
  });
}