// ignore_for_file: must_be_immutable, deprecated_member_use

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:lba/gen/assets.gen.dart';
import 'package:lba/res/colors.dart';
import 'package:lba/widgets/buildWarpedInfo.dart';
import 'package:lba/widgets/orderType.dart';
import 'package:lba/widgets/rate.dart';
import 'package:lba/widgets/reviews.dart';

class Item extends StatefulWidget {
  String title;
  String brand;
  String dimensions;
  String colour;
  String material;
  String description;

  Item({
    super.key,
    required this.title,
    required this.brand,
    required this.dimensions,
    required this.colour,
    required this.material,
    required this.description,
  });

  @override
  State<Item> createState() => _ItemState();
}

class _ItemState extends State<Item> with TickerProviderStateMixin {
  bool showAllReviews = false;
  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();

  late AnimationController _staggeredController;
  late List<Animation<double>> _staggeredAnimations;

  final List<Map<String, dynamic>> reviews = [
    {
      "name": "Sara M",
      "comment":
          '"Super happy with my new sofa from Chattels & More! 🙻✨ Great quality, smooth delivery, and helpful staff. Totally worth it!" 😍👌',
      "rate": 5.0,
      "yesCount": 2,
      "noCount": 0,
      "date": "Jun 09, 2025",
    },
    {
      "name": "Khalid A",
      "comment":
          '"Nice design but poor delivery experience 😕🕐 Had to wait extra days and deal with missing parts. Expected better for the price." 👎💸',
      "rate": 1.0,
      "yesCount": 5,
      "noCount": 10,
      "date": "Dec 26, 2024",
    },
    {
      "name": "Khalid A",
      "comment":
          '"Nice design but poor delivery experience 😕🕐 Had to wait extra days and deal with missing parts. Expected better for the price." 👎💸',
      "rate": 3.0,
      "yesCount": 5,
      "noCount": 10,
      "date": "Dec 26, 2024",
    },
    {
      "name": "Sara M",
      "comment":
          '"Super happy with my new sofa from Chattels & More! 🙻✨ Great quality, smooth delivery, and helpful staff. Totally worth it!" 😍👌',
      "rate": 4.0,
      "yesCount": 2,
      "noCount": 0,
      "date": "Jun 09, 2025",
    },
  ];

  List<Map<String, dynamic>> displayedReviews = [];

  @override
  void initState() {
    super.initState();
    displayedReviews = reviews.length > 2 ? reviews.sublist(0, 2) : List.from(reviews);

    _staggeredController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1200),
    );

    // --- FIX: Changed itemCount from 7 to 8 ---
    final int itemCount = 8;
    _staggeredAnimations = List.generate(itemCount, (index) {
      return Tween<double>(begin: 0.0, end: 1.0).animate(
        CurvedAnimation(
          parent: _staggeredController,
          curve: Interval(
            (0.1 * index),
            (0.5 + 0.1 * index).clamp(0.0, 1.0),
            curve: Curves.easeOutCubic,
          ),
        ),
      );
    });

    _staggeredController.forward();
  }
  
  @override
  void dispose() {
    _staggeredController.dispose();
    super.dispose();
  }

  void _showAllReviewsWithAnimation() async {
    final newItems = reviews.sublist(displayedReviews.length);
    for (int i = 0; i < newItems.length; i++) {
      await Future.delayed(Duration(milliseconds: 150)); 
      displayedReviews.add(newItems[i]);
      _listKey.currentState?.insertItem(displayedReviews.length - 1);
      setState(() {}); 
    }
    setState(() {
      showAllReviews = true;
    });
  }

  Widget _buildAnimatedWidget(Widget child, int index) {
    return FadeTransition(
      opacity: _staggeredAnimations[index],
      child: SlideTransition(
        position: Tween<Offset>(
          begin: const Offset(0.0, 0.3),
          end: Offset.zero,
        ).animate(_staggeredAnimations[index]),
        child: child,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildAnimatedWidget(
              Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  widget.title,
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                ),
              ),
              0,
            ),
            SizedBox(height: 5),
            _buildAnimatedWidget(
              Row(
                children: [
                  Text("Brand: "),
                  Expanded(
                    child: Text(
                      widget.brand,
                      style: TextStyle(color: LightAppColors.primary),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              1,
            ),
            SizedBox(height: 10),
            _buildAnimatedWidget(
              Row(
                children: [
                  CustomStarRating(rating: 4.8),
                  SizedBox(width: 3),
                  Text(
                    "4.8",
                    style: TextStyle(color: LightAppColors.productDetailDivider),
                  ),
                ],
              ),
              2,
            ),
            SizedBox(height: 15),
            _buildAnimatedWidget(
              Row(
                children: [
                  OrderType(
                    icon: Assets.icons.cardPos.path,
                    typename: "Delivery",
                    fill: true,
                  ),
                  SizedBox(width: 7),
                  OrderType(
                    icon: Assets.icons.shoppingCart.path,
                    typename: "Pickup",
                    fill: true,
                  ),
                ],
              ),
              3,
            ),
            SizedBox(height: 15),
            _buildAnimatedWidget(buildWrappedInfo("Dimensions:", widget.dimensions), 4),
            _buildAnimatedWidget(buildWrappedInfo("Colour:", widget.colour), 5),
            _buildAnimatedWidget(buildWrappedInfo("Material:", widget.material), 6),
            _buildAnimatedWidget(buildWrappedInfo("Description:", widget.description), 7), // Now this is valid
            SizedBox(height: 30),
            Center(
              child: Text(
                "Top reviews from the United Arab Emirates",
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
            SizedBox(height: 15),

            AnimatedList(
              key: _listKey,
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              initialItemCount: displayedReviews.length,
              itemBuilder: (context, index, animation) {
                final review = displayedReviews[index];
                return SlideTransition(
                  position: Tween<Offset>(
                    begin: const Offset(-1, 0),
                    end: Offset.zero,
                  ).animate(CurvedAnimation(parent: animation, curve: Curves.easeInOut)),
                  child: SizeTransition(
                    sizeFactor: animation,
                    axisAlignment: -1,
                    child: Reviews(
                      name: review['name'],
                      comment: review['comment'],
                      rate: review['rate'],
                      yesCount: review['yesCount'],
                      noCount: review['noCount'],
                      date: review['date'],
                    ),
                  ),
                );
              },
            ),

            if (!showAllReviews && reviews.length > 2)
              Column(
                children: [
                  Center(
                    child: InkWell(
                      onTap: _showAllReviewsWithAnimation,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "See all reviews",
                            style: TextStyle(
                              color: LightAppColors.allReviewOpener,
                              fontWeight: FontWeight.bold,
                              fontSize: 18,
                            ),
                          ),
                          SizedBox(width: 10),
                          SvgPicture.asset(
                            Assets.icons.arrowDown.path,
                            color: LightAppColors.allReviewOpener,
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: 50,)
                ],
              ),
          ],
        ),
      ),
    );
  }
}