// ignore_for_file: unused_local_variable, deprecated_member_use

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:lba/data/model/workingHours.dart';
import 'package:lba/gen/assets.gen.dart';
import 'package:lba/res/colors.dart';
import 'package:lba/widgets/customCard.dart';
import 'package:lba/widgets/dividerTitle.dart';
import 'package:lba/widgets/openChecker.dart';
import 'package:lba/widgets/rate.dart';
import 'package:lba/widgets/similar_business_card.dart';
import 'package:maps_launcher/maps_launcher.dart';

class Shop extends StatefulWidget {
  final String shopName;
  final double star;
  final String place;
  final List<String> branches;
  final List<WorkingHours> workingHours;
  final String facilities;

  const Shop({
    super.key,
    required this.shopName,
    required this.star,
    required this.place,
    required this.branches,
    required this.workingHours,
    required this.facilities,
  });

  @override
  State<Shop> createState() => _ShopState();
}

class _ShopState extends State<Shop> with TickerProviderStateMixin {
  late String selectedPlace;
  bool isActiveOffer = true;

  late AnimationController _staggeredController;
  late List<Animation<double>> _staggeredAnimations;
  late AnimationController _listAnimationController;
  late List<Animation<double>> _itemAnimations;
  late AnimationController _similarBusinessAnimationController;
  late List<Animation<double>> _similarBusinessAnimations;

  final List<Map<String, String>> similarBusinesses = [
    {
      "imagePath": Assets.images.wp1929534FastFoodWallpapers1.path,
      "name": "The Odd Piece",
      "location": "Al Quoz 1",
    },
    {
      "imagePath": Assets.images.topDealsAndStores.path,
      "name": "IKEA",
      "location": "Dubai Festival City",
    },
    {
      "imagePath": Assets.images.media.path,
      "name": "Home Centre",
      "location": "Mall of the Emirates",
    }
  ];

  @override
  void initState() {
    super.initState();
    selectedPlace = widget.place;

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

    _listAnimationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1000),
    );

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

    final int itemCount = 9;
    _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,
          ),
        ),
      );
    });

    _itemAnimations = List.generate(2, (index) {
      return Tween<double>(begin: 0.0, end: 1.0).animate(
        CurvedAnimation(
          parent: _listAnimationController,
          curve: Interval(
            (0.2 * index),
            (0.6 + 0.2 * index).clamp(0.0, 1.0),
            curve: Curves.easeOut,
          ),
        ),
      );
    });

    _similarBusinessAnimations =
        List.generate(similarBusinesses.length, (index) {
      return Tween<double>(begin: 0.0, end: 1.0).animate(
        CurvedAnimation(
          parent: _similarBusinessAnimationController,
          curve: Interval(
            (0.2 * index),
            (0.6 + 0.2 * index).clamp(0.0, 1.0),
            curve: Curves.easeOut,
          ),
        ),
      );
    });

    _staggeredController.forward();
    _listAnimationController.forward();
    _similarBusinessAnimationController.forward();
  }

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

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

  @override
  Widget build(BuildContext context) {
    final now = DateTime.now();
    final schedule = IsOpenChecker.getTodaySchedule(widget.workingHours);
    final isOpen = IsOpenChecker.isOpenNow(widget.workingHours);

    String timeRange = '';
    if (isOpen && schedule.shifts.isNotEmpty) {
      for (final shift in schedule.shifts) {
        timeRange +=
            '${formatTime12Hour(shift.openAt)} - ${formatTime12Hour(shift.closeAt)}  ';
      }
    }

    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildAnimatedWidget(
              Row(
                children: [
                  SvgPicture.asset(
                    Assets.icons.shop.path,
                    color: AppColors.isDarkMode ? Colors.white : AppColors.textPrimary,
                    height: 25,
                  ),
                  const SizedBox(width: 10),
                  Text(
                    widget.shopName,
                    style: const TextStyle(
                        fontWeight: FontWeight.bold, fontSize: 17),
                  ),
                ],
              ),
              0,
            ),
            const SizedBox(height: 15),
            _buildAnimatedWidget(
              Row(
                children: [
                  CustomStarRating(rating: widget.star),
                  const SizedBox(width: 5),
                  Text(
                    widget.star.toString(),
                    style: const TextStyle(
                      color: LightAppColors.productDetailDivider,
                    ),
                  ),
                ],
              ),
              1,
            ),
            const SizedBox(height: 5),
            _buildAnimatedWidget(
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      SvgPicture.asset(
                        Assets.icons.location.path,
                        color: AppColors.isDarkMode ? Colors.white : AppColors.textPrimary,
                      ),
                      const SizedBox(width: 5),
                      Text(
                        selectedPlace,
                        style: TextStyle(
                          color: AppColors.productDetailDivider,
                        ),
                      ),
                    ],
                  ),
                  PopupMenuButton<String>(
                    color: AppColors.surface,
                    icon: SvgPicture.asset(
                      Assets.icons.arrowDown.path,
                      color: AppColors.isDarkMode ? Colors.white : AppColors.textPrimary,
                      height: 20,
                    ),
                    onSelected: (String newPlace) {
                      setState(() {
                        selectedPlace = newPlace;
                      });
                    },
                    itemBuilder: (BuildContext context) {
                      return widget.branches.map((String branch) {
                        return PopupMenuItem<String>(
                          value: branch,
                          child: Text(branch),
                        );
                      }).toList();
                    },
                  ),
                ],
              ),
              2,
            ),
            const SizedBox(height: 5),
            _buildAnimatedWidget(
              Row(
                children: [
                  SvgPicture.asset(Assets.icons.clock.path, 
                    color: AppColors.isDarkMode ? Colors.white : null),
                  const SizedBox(width: 5),
                  Text(
                    isOpen ? 'Open Now' : 'Closed',
                    style: TextStyle(color: isOpen ? AppColors.confirmButton : AppColors.errorColor),
                  ),
                  const SizedBox(width: 5),
                  isOpen? Container(
                    color: AppColors.productDetailDivider,
                    width: 1,
                    height: 13,
                  ) : SizedBox(),
                  const SizedBox(width: 5),
                  Text(
                    timeRange,
                    style: TextStyle(
                      color: AppColors.productDetailDivider,
                    ),
                  ),
                ],
              ),
              3,
            ),
            const SizedBox(height: 15),
            _buildAnimatedWidget(
                const DividerTitleWidget(title: "Facilities"), 4),
            _buildAnimatedWidget(
              SizedBox(
                height: 50,
                child: ListView.builder(
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: 1,
                  itemBuilder: (context, index) {
                    return Row(
                      children: [
                        SvgPicture.asset(Assets.icons.tick.path,
                          color: AppColors.isDarkMode ? Colors.white : null),
                        const SizedBox(width: 5),
                        Text(
                          widget.facilities,
                          style: TextStyle(
                            color: AppColors.productDetailDivider,
                          ),
                        ),
                      ],
                    );
                  },
                ),
              ),
              5,
            ),
            const SizedBox(height: 20),
            _buildAnimatedWidget(
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.confirmButton,
                  minimumSize: const Size(double.infinity, 48),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15),
                  ),
                ),
                onPressed: () {
                  MapsLauncher.launchCoordinates(25.2399, 55.2744);
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SvgPicture.asset(
                      Assets.icons.routing2.path,
                      color: AppColors.isDarkMode ? Colors.white : AppColors.textPrimary,
                    ),
                    const SizedBox(width: 5),
                    Text(
                      "Direction",
                      style: TextStyle(color: AppColors.textPrimary, fontSize: 16),
                    ),
                  ],
                ),
              ),
              6,
            ),
            const SizedBox(height: 30),
            _buildAnimatedWidget(
              const Text(
                "List of offers",
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
              ),
              7,
            ),
            const SizedBox(height: 15),
            _buildAnimatedWidget(
              Container(
                height: 45,
                width: 150,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                  color: isActiveOffer 
                    ? AppColors.activeOfferBackground 
                    : AppColors.oldOfferBackground,
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            isActiveOffer = true;
                          });
                        },
                        child: Padding(
                          padding: const EdgeInsets.all(3.0),
                          child: Container(
                            height: 35,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color:
                                  isActiveOffer ? AppColors.surface : Colors.transparent,
                            ),
                            child: Center(
                              child: Text(
                                "Active",
                                style: TextStyle(
                                  color: isActiveOffer 
                                    ? AppColors.textPrimary 
                                    : AppColors.textSecondary,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            isActiveOffer = false;
                          });
                        },
                        child: Padding(
                          padding: const EdgeInsets.all(3.0),
                          child: Container(
                            height: 35,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color:
                                  !isActiveOffer ? AppColors.surface : Colors.transparent,
                            ),
                            child: Center(
                              child: Text(
                                "Old",
                                style: TextStyle(
                                  color: !isActiveOffer 
                                    ? AppColors.textPrimary 
                                    : AppColors.textSecondary,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              8,
            ),
            const SizedBox(height: 15),
            SizedBox(
              height: 160,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                shrinkWrap: true,
                itemCount: 2,
                itemBuilder: (context, index) {
                  return FadeTransition(
                    opacity: _itemAnimations[index],
                    child: SlideTransition(
                      position: Tween<Offset>(
                        begin: const Offset(0.5, 0.0),
                        end: Offset.zero,
                      ).animate(_itemAnimations[index]),
                      child: ColorFiltered(
                        colorFilter: !isActiveOffer
                            ? const ColorFilter.matrix(<double>[
                                0.2126,
                                0.7152,
                                0.0722,
                                0,
                                0,
                                0.2126,
                                0.7152,
                                0.0722,
                                0,
                                0,
                                0.2126,
                                0.7152,
                                0.0722,
                                0,
                                0,
                                0,
                                0,
                                0,
                                1,
                                0,
                              ])
                            : const ColorFilter.mode(
                                Colors.transparent,
                                BlendMode.multiply,
                              ),
                        child: const CustomCard(
                          title: "Calamaro Table Lamp",
                          description: "Elegant lighting with a modern twist.",
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
            const SizedBox(height: 20),
            const Text(
              "Similar Business",
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
            ),
            const SizedBox(height: 15),
            SizedBox(
              height: 280,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: similarBusinesses.length,
                itemBuilder: (context, index) {
                  final business = similarBusinesses[index];
                  return FadeTransition(
                    opacity: _similarBusinessAnimations[index],
                    child: SlideTransition(
                      position: Tween<Offset>(
                        begin: const Offset(0.5, 0.0),
                        end: Offset.zero,
                      ).animate(_similarBusinessAnimations[index]),
                      child: SimilarBusinessCard(
                        imagePath: business['imagePath']!,
                        name: business['name']!,
                        location: business['location']!,
                        onTap: () {
                          print("${business['name']} tapped!");
                        },
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}