// ignore_for_file: 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/screens/mains/nearby/mainNearby/listScreen.dart';
import 'package:lba/screens/mains/nearby/mainNearby/map.dart';
import 'package:lba/screens/product/productdetail.dart';
import 'package:lba/widgets/customBottomSheet.dart';
import 'package:lba/widgets/gpsPopup.dart';

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

  @override
  State<Nearby> createState() => _NearbyState();
}

class _NearbyState extends State<Nearby> with TickerProviderStateMixin {
  String selectedOption = "Relevance";
  final List<String> options = ["Relevance", "Newest", "Oldest", "Popularity"];
  int selectedIndex = 1;
  List<String> selectedOptions = [];

  late AnimationController _listAnimationController;

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      if (mounted) {
        showGPSDialog(context);
      }
    });

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

    if (selectedIndex == 1) {
      _listAnimationController.forward();
    }
  }

  @override
  void dispose() {
    _listAnimationController.dispose();
    super.dispose();
  }
  
  void _onToggle(int index) {
    setState(() {
      selectedIndex = index;
    });

    if (index == 1) {
      _listAnimationController.forward(from: 0.0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 70,
        shadowColor: Colors.grey,
        elevation: 2,
        automaticallyImplyLeading: false,
        title: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child: SizedBox(
                      height: 40,
                      child: TextField(
                        decoration: InputDecoration(
                          hintText: 'What are you looking for?',
                          hintStyle: const TextStyle(
                            color: Colors.grey,
                            fontSize: 13,
                          ),
                          prefixIcon: Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: SvgPicture.asset(
                              Assets.icons.riSearch2Line.path,
                              width: 18,
                              height: 18,
                            ),
                          ),
                          filled: true,
                          fillColor: const Color.fromARGB(255, 248, 248, 248),
                          contentPadding: const EdgeInsets.symmetric(
                            horizontal: 16.0,
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12.0),
                            borderSide: const BorderSide(
                              color: Color.fromARGB(255, 14, 63, 102),
                              width: 2.0,
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12.0),
                            borderSide: const BorderSide(
                              color: Color.fromARGB(255, 14, 63, 102),
                              width: 1.0,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 10),
                  _buildIconButton(
                    icon: Assets.icons.sort.path,
                    onPressed: () {
                      CustomBottomSheet.show(context, [
                        "Food & Dining",
                        "Entertainment & Leisure",
                        "Health & Fitness",
                        "Travel & Transportation",
                      ]);
                    },
                  ),
                  const SizedBox(width: 8),
                  _buildIconButton(
                    icon: Assets.icons.location.path,
                    onPressed: () {},
                  ),
                ],
              ),
            ],
          ),
        ),
        backgroundColor: Colors.white,
      ),
      body: Column(
        children: [
          _buildToggleButtons(),
          Container(
            width: 350,
            height: 3,
            color: const Color.fromARGB(255, 14, 63, 102),
          ),
          Expanded(
            child: AnimatedSwitcher(
              duration: const Duration(milliseconds: 500),
              transitionBuilder: (Widget child, Animation<double> animation) {
                final slideAnimation = Tween<Offset>(
                  begin: Offset(child.key == const ValueKey('list') ? -1.0 : 1.0, 0.0),
                  end: Offset.zero,
                ).animate(CurvedAnimation(parent: animation, curve: Curves.easeInOutCubic));

                return ClipRect(
                  child: SlideTransition(
                    position: slideAnimation,
                    child: FadeTransition(
                      opacity: animation,
                      child: child,
                    ),
                  ),
                );
              },
              child: selectedIndex == 1
                  ? _buildListContent(key: const ValueKey('list'))
                  : const CustomMap(key: ValueKey('map')),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildIconButton({
    required String icon,
    required VoidCallback onPressed,
  }) {
    return Container(
      width: 40,
      height: 40,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color.fromARGB(255, 14, 63, 102),
          width: 1.5,
        ),
      ),
      child: IconButton(
        icon: SvgPicture.asset(icon),
        onPressed: onPressed,
        padding: const EdgeInsets.all(8),
      ),
    );
  }

  Widget _buildToggleButtons() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
      child: SizedBox(
        width: 350,
        height: 60,
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            Positioned(
              left: 50,
              right: 50,
              child: Container(
                height: 50,
                width: 170,
                color: const Color.fromARGB(255, 234, 234, 233),
              ),
            ),
            Positioned(
              left: 0,
              child: _buildToggleButton(
                color: selectedIndex == 1
                    ? const Color.fromARGB(255, 10, 69, 117)
                    : const Color.fromARGB(100, 177, 177, 177),
                icon: Assets.icons.elementEqual.path,
                iconColor: selectedIndex == 1
                    ? const Color.fromARGB(255, 234, 245, 254)
                    : const Color.fromARGB(255, 157, 157, 155),
                text: 'list',
                isSelected: selectedIndex == 1,
                onTap: () => _onToggle(1),
                borderRadius: BorderRadius.only(
                  topLeft: const Radius.circular(12),
                  bottomLeft: const Radius.circular(12),
                  topRight:
                      selectedIndex == 1 ? const Radius.circular(12) : Radius.zero,
                  bottomRight:
                      selectedIndex == 1 ? const Radius.circular(12) : Radius.zero,
                ),
              ),
            ),
            Positioned(
              right: 0,
              child: _buildToggleButton(
                color: selectedIndex == 0
                    ? const Color.fromARGB(255, 10, 69, 117)
                    : const Color.fromARGB(100, 177, 177, 177),
                iconColor: selectedIndex == 0
                    ? const Color.fromARGB(255, 234, 245, 254)
                    : const Color.fromARGB(255, 157, 157, 155),
                icon: Assets.icons.mapSelected.path,
                text: 'map',
                isSelected: selectedIndex == 0,
                onTap: () => _onToggle(0),
                borderRadius: BorderRadius.only(
                  topRight: const Radius.circular(12),
                  bottomRight: const Radius.circular(12),
                  bottomLeft:
                      selectedIndex == 0 ? const Radius.circular(12) : Radius.zero,
                  topLeft:
                      selectedIndex == 0 ? const Radius.circular(12) : Radius.zero,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildListContent({Key? key}) {
    final listItems = [
      ListScreen(
        delivery: true,
        pickup: false,
        expiryTimeString: "2025-05-19T13:30:49.623619357Z",
        ontap: () {
          Navigator.of(context).push(
            MaterialPageRoute(builder: (context) => const Productdetail()),
          );
        },
      ),
      ListScreen(
        delivery: false,
        pickup: true,
        expiryTimeString: "2025-05-25T05:20:49.623619357Z",
      ),
      ListScreen(
        delivery: true,
        pickup: true,
        expiryTimeString: "2025-05-12T13:20:37.435249520Z",
      ),
    ];

    return SingleChildScrollView(
      key: key,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(30, 5, 30, 0),
        child: Column(
          children: [
            Row(
              children: [
                const Text(
                  "Sort by:",
                  style: TextStyle(fontWeight: FontWeight.w600),
                ),
                const SizedBox(width: 10),
                DropdownButton<String>(
                  value: selectedOption,
                  icon: Padding(
                    padding: const EdgeInsets.only(left: 6),
                    child: SvgPicture.asset(Assets.icons.arrowDown.path),
                  ),
                  elevation: 16,
                  dropdownColor: Colors.white,
                  style: const TextStyle(
                    color: Color.fromARGB(255, 33, 150, 243),
                    fontWeight: FontWeight.w500,
                  ),
                  underline: const SizedBox(),
                  onChanged: (String? newValue) {
                    setState(() {
                      selectedOption = newValue!;
                    });
                  },
                  items:
                      options.map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                    );
                  }).toList(),
                ),
              ],
            ),
            const SizedBox(height: 10),
            ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: listItems.length,
              itemBuilder: (context, index) {
                final animation = Tween<double>(begin: 0.0, end: 1.0).animate(
                  CurvedAnimation(
                    parent: _listAnimationController,
                    curve: Interval(
                      (0.1 * index),
                      (0.5 + 0.1 * index).clamp(0.0, 1.0),
                      curve: Curves.easeOutCubic,
                    ),
                  ),
                );
                return FadeTransition(
                  opacity: animation,
                  child: SlideTransition(
                    position: Tween<Offset>(
                      begin: const Offset(0, 0.5),
                      end: Offset.zero,
                    ).animate(animation),
                    child: listItems[index],
                  ),
                );
              },
            ),
            const SizedBox(height: 90),
          ],
        ),
      ),
    );
  }

  Widget _buildToggleButton({
    required String text,
    required bool isSelected,
    required VoidCallback onTap,
    required BorderRadius borderRadius,
    required Color color,
    required String icon,
    required Color iconColor,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Stack(
        children: [
          Container(
            width: 170,
            height: 50,
            decoration: BoxDecoration(
              borderRadius: borderRadius,
              color: isSelected
                  ? const Color.fromARGB(255, 14, 63, 102)
                  : const Color.fromARGB(255, 234, 234, 233),
              boxShadow: isSelected
                  ? [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.2),
                        spreadRadius: 1,
                        blurRadius: 4,
                        offset: const Offset(0, 2),
                      ),
                    ]
                  : null,
            ),
            alignment: Alignment.center,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: 30,
                  height: 30,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: color,
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(1.0),
                    child: Center(
                      child: SvgPicture.asset(icon, color: iconColor),
                    ),
                  ),
                ),
                const SizedBox(width: 10),
                Text(
                  text,
                  style: TextStyle(
                    color: isSelected ? Colors.white : Colors.black87,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
          if (isSelected)
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: SvgPicture.asset(Assets.icons.shape.path, height: 4),
            ),
        ],
      ),
    );
  }
}