import 'package:Intaleq/views/widgets/my_textField.dart';

import 'package:flutter/cupertino.dart';

import 'package:flutter/material.dart';

import 'package:get/get.dart';

import 'package:Intaleq/constant/box_name.dart';

import 'package:Intaleq/constant/style.dart';

import 'package:Intaleq/controller/home/map_passenger_controller.dart';

import 'package:Intaleq/main.dart';

import 'package:Intaleq/views/home/map_widget.dart/form_search_places_destenation.dart';

import 'package:Intaleq/views/widgets/elevated_btn.dart';

import 'package:google_maps_flutter/google_maps_flutter.dart';

import '../../../constant/colors.dart';

import '../../../constant/table_names.dart';

import '../../../controller/functions/toast.dart';

import '../../../controller/functions/tts.dart';

import '../../widgets/error_snakbar.dart';

import '../../widgets/mydialoug.dart';

import 'form_search_start.dart';

class MainBottomMenuMap extends StatelessWidget {
  const MainBottomMenuMap({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(MapPassengerController());

    return GetBuilder<MapPassengerController>(
      builder: (controller) => Positioned(
        bottom: Get.height * .04, // Increased bottom padding

        left: 16,

        right: 16,

        child: GestureDetector(
          onTap: controller
              .changeMainBottomMenuMap, // Make the whole area tappable

          child: AnimatedContainer(
            duration: const Duration(
                milliseconds: 300), // Reduced duration for smoother animation

            curve: Curves.easeInOut, // Added animation curve

            height: controller.mainBottomMenuMapHeight,

            decoration: BoxDecoration(
              color: AppColor.secondaryColor, // Use a solid background color

              borderRadius: BorderRadius.circular(16), // More rounded corners

              boxShadow: [
                BoxShadow(
                  color: Colors.black12,
                  blurRadius: 10,
                  offset: Offset(0, 5),
                ),
              ],
            ),

            child: SingleChildScrollView(
              physics: const BouncingScrollPhysics(), // Add bouncing effect

              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,

                crossAxisAlignment: CrossAxisAlignment
                    .stretch, // Stretch children to full width

                children: [
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          controller.isMainBottomMenuMap
                              ? 'Where are you going?'.tr
                              : 'Quick Actions'.tr,
                          style: AppStyle.title
                              .copyWith(fontWeight: FontWeight.bold),
                        ),
                        IconButton(
                          onPressed: controller.changeMainBottomMenuMap,
                          icon: Icon(
                            controller.isMainBottomMenuMap
                                ? Icons.keyboard_arrow_down_rounded
                                : Icons.keyboard_arrow_up_rounded,
                            size: 28,
                            color: AppColor.primaryColor,
                          ),
                        ),
                      ],
                    ),
                  ),
                  if (controller.isMainBottomMenuMap) ...[
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16.0),
                      child: InkWell(
                        onTap: () => controller.changeMainBottomMenuMap(),
                        child: Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: AppColor.primaryColor
                                .withOpacity(0.05), // Subtle background

                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: DefaultTextStyle(
                            style: AppStyle.subtitle
                                .copyWith(color: AppColor.writeColor),
                            child: Center(
                              child: controller.isPickerShown
                                  ? clickPointPosition(controller, context)
                                  : whereWidgetSmall(controller),
                            ),
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                    if (controller.recentPlaces.isNotEmpty)
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 8.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
// Text('Recent Places'.tr, style: AppStyle.subtitle),

                            SizedBox(
                              height: 30,
                              child: Center(
                                child: ListView.separated(
                                  scrollDirection: Axis.horizontal,
                                  itemCount: controller.recentPlaces.length,
                                  separatorBuilder: (context, index) =>
                                      const SizedBox(width: 8),
                                  itemBuilder: (context, index) =>
                                      _buildRecentPlaceButton(
                                          controller, context, index),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                  ] else ...[
                    if (!controller.isAnotherOreder)
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16.0),
                        child: Text(
                          '${'From:'.tr} ${controller.currentLocationString}'
                              .tr,
                          style: AppStyle.subtitle,
                        ),
                      ),
                    const SizedBox(height: 8),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16.0),
                      child: !controller.isAnotherOreder
                          ? const SizedBox()
                          : formSearchPlacesStart(),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16.0),
                      child: formSearchPlacesDestenation(),
                    ),
                    const SizedBox(height: 16),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16.0),
                      child: GestureDetector(
                        onTap: () {
                          Get.dialog(
                            AlertDialog(
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(16)),
                              title: Text('WhatsApp Location Extractor'.tr),
                              content: Form(
                                key: controller.sosFormKey,
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    MyTextForm(
                                      controller:
                                          controller.whatsAppLocationText,
                                      label: 'Location Link'.tr,
                                      hint: 'Paste location link here'.tr,
                                      type: TextInputType.url,
                                    ),
                                    const SizedBox(height: 16),
                                    MyElevatedButton(
                                      title: 'Go to this location'.tr,
                                      onPressed: () async {
                                        controller.goToWhatappLocation();
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.blue.shade100, // Lighter background

                            borderRadius: BorderRadius.circular(12),

                            border: Border.all(
                                color: Colors.blue.shade400), // Add a border
                          ),
                          padding: const EdgeInsets.all(16),
                          child: Row(
                            children: [
                              Icon(Icons.link, color: Colors.blue.shade700),
                              const SizedBox(width: 8),
                              Expanded(
                                child: Text(
                                  'Paste WhatsApp location link'.tr,
                                  style: TextStyle(color: Colors.blue.shade700),
                                ),
                              ),
                              const Icon(Icons.arrow_forward_ios_rounded,
                                  size: 16, color: Colors.blueGrey),
                            ],
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16.0),
                      child: OutlinedButton(
                        onPressed: () {
                          showCupertinoModalPopup(
                            context: context,
                            builder: (BuildContext context) =>
                                CupertinoActionSheet(
                              title: Text('Select Order Type'.tr),
                              message: Text('Choose who this order is for'.tr),
                              actions: <Widget>[
                                CupertinoActionSheetAction(
                                  child: Text('I want to order for myself'.tr),
                                  onPressed: () {
                                    controller.changeisAnotherOreder(false);

                                    Navigator.pop(context);
                                  },
                                ),
                                CupertinoActionSheetAction(
                                  child: Text(
                                      'I want to order for someone else'.tr),
                                  onPressed: () {
                                    controller.changeisAnotherOreder(true);

                                    Navigator.pop(context);
                                  },
                                ),
                              ],
                              cancelButton: CupertinoActionSheetAction(
                                isDefaultAction: true,
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                                child: Text('Cancel'.tr),
                              ),
                            ),
                          );
                        },
                        child: Text(
                          !controller.isAnotherOreder
                              ? 'Order for someone else'.tr
                              : 'Order for myself'.tr,
                        ),
                      ),
                    ),
                  ],
                  const SizedBox(height: 8),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildRecentPlaceButton(
      MapPassengerController controller, BuildContext context, int index) {
    final textToSpeechController = Get.find<TextToSpeechController>();

    return InkWell(
      onTap: () {
        MyDialog().getDialog('Are you want to go this site'.tr, ' ', () async {
          Get.back();

          await controller.getLocation();

          await controller.getDirectionMap(
            '${controller.passengerLocation.latitude},${controller.passengerLocation.longitude}',
            '${controller.recentPlaces[index]['latitude']},${controller.recentPlaces[index]['longitude']}',
          );

          controller.showBottomSheet1();
        });
      },
      onLongPress: () {
        MyDialog().getDialog(
          "Are you sure to delete this location?".tr,
          '',
          () {
            sql.deleteData(TableName.recentLocations,
                controller.recentPlaces[index]['id']);

            controller.getFavioratePlaces();

            controller.update();

            Get.back();

            mySnackbarSuccess('deleted'.tr);
          },
        );
      },
      child: Container(
        decoration: BoxDecoration(
          color: AppColor.primaryColor.withOpacity(0.05), // Subtle background

          borderRadius: BorderRadius.circular(12),

          border: Border(
            bottom: BorderSide(
                color: AppColor.primaryColor.withOpacity(0.1), width: 1),
          ),
        ),
        child: Text(controller.recentPlaces[index]['name'],
            style: const TextStyle(fontSize: 14)),
      ),
    );
  }

  Widget clickPointPosition(
      MapPassengerController controller, BuildContext context) {
    return TextButton(
      onPressed: () async {
        controller.clearPolyline();

        controller.data = [];

        if (controller.passengerStartLocationFromMap == true) {
          controller.newMyLocation = controller.newStartPointLocation;

          controller.changeMainBottomMenuMap();

          await controller.getDirectionMap(
            '${controller.newStartPointLocation.latitude},${controller.newStartPointLocation.longitude}',
            '${controller.myDestination.latitude},${controller.myDestination.longitude}',
          );

          controller.currentLocationToFormPlaces = false;

          controller.placesDestination = [];

          controller.clearPlacesStart();

          controller.clearPlacesDestination();

          controller.passengerStartLocationFromMap = false;

          controller.isPickerShown = false;

          controller.showBottomSheet1();
        } else if (controller.startLocationFromMap == true) {
          controller.newMyLocation = controller.newStartPointLocation;

          controller.hintTextStartPoint =
              '${controller.newStartPointLocation.latitude.toStringAsFixed(4)} , ${controller.newStartPointLocation.longitude.toStringAsFixed(4)}';

          controller.startLocationFromMap = false;

          controller.isPickerShown = false;
        } else if (controller.workLocationFromMap == true) {
          controller.hintTextDestinationPoint = 'To Work'.tr;

          box.write(BoxName.addWork,
              '${controller.newMyLocation.latitude.toStringAsFixed(4)} , ${controller.newMyLocation.longitude.toStringAsFixed(4)}');

          controller.newMyLocation = controller.newMyLocation;

          controller.isPickerShown = false;

          controller.workLocationFromMap = false;

          Get.snackbar('Work Saved'.tr, '',
              backgroundColor: AppColor.greenColor);
        } else if (controller.homeLocationFromMap == true) {
          controller.hintTextDestinationPoint = 'To Home'.tr;

          box.write(BoxName.addHome,
              '${controller.newMyLocation.latitude.toStringAsFixed(4)} , ${controller.newMyLocation.longitude.toStringAsFixed(4)}');

          controller.newMyLocation = controller.newMyLocation;

          controller.isPickerShown = false;

          controller.homeLocationFromMap = false;

          controller.update();

          Get.snackbar('Home Saved'.tr, '',
              backgroundColor: AppColor.greenColor);
        } else {
          controller.hintTextDestinationPoint =
              '${controller.newMyLocation.latitude.toStringAsFixed(4)} , ${controller.newMyLocation.longitude.toStringAsFixed(4)}';

          controller.myDestination = controller.newMyLocation;

          controller.isPickerShown = false;

          controller.changeMainBottomMenuMap();

          controller.passengerStartLocationFromMap = true;

          controller.isPickerShown = true;

          if (controller.isAnotherOreder == false) {
            await controller.mapController?.animateCamera(
                CameraUpdate.newLatLng(LatLng(
                    controller.passengerLocation.latitude,
                    controller.passengerLocation.longitude)));

            Get.defaultDialog(
                title: 'Destination selected'.tr,
                titleStyle: AppStyle.title,
                content: Text(
                  'Now select start pick'.tr,
                  style: AppStyle.title,
                ),
                confirm: MyElevatedButton(
                    title: 'OK'.tr,
                    onPressed: () {
                      Get.back();
                    }));
          }

          if (controller.isWhatsAppOrder == true) {
            Get.defaultDialog(
                title: 'Destination selected'.tr,
                titleStyle: AppStyle.title,
                content: Text(
                  'Now select start pick'.tr,
                  style: AppStyle.title,
                ),
                confirm: MyElevatedButton(
                    title: 'OK'.tr,
                    onPressed: () {
                      Get.back();
                    }));
          }
        }

        controller.placesDestination = [];

        controller.placeDestinationController.clear();

        // controller.showBottomSheet1();

        controller.changeMainBottomMenuMap();
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 8.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              controller.passengerStartLocationFromMap
                  ? Icons.location_on
                  : Icons.location_searching,
              size: 20,
              color: AppColor.primaryColor,
            ),
            const SizedBox(width: 8),
            Text(
              controller.passengerStartLocationFromMap
                  ? 'Confirm Pick-up Location'.tr
                  : "Set Location on Map".tr,
              style: AppStyle.subtitle.copyWith(
                fontWeight: FontWeight.bold,
                color: AppColor.primaryColor,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget whereWidgetSmall(MapPassengerController controller) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(Icons.location_searching, color: AppColor.primaryColor),
        const SizedBox(width: 8),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
                '${'Where to'.tr} ${(box.read(BoxName.name).toString().split(' ')[0])} ',
                style: AppStyle.subtitle),

// if (controller.noCarString)

// Text('Nearest Car: ~'.tr,

// style: TextStyle(color: Colors.grey.shade600))

// else

            // Text(
            //   controller.nearestCar != null
            //       ? 'Nearest Car: ${controller.nearestDistance.toStringAsFixed(0)} m'
            //       : 'No cars nearby'.tr,
            //   style: TextStyle(color: Colors.grey.shade600),
            // ),
          ],
        ),
      ],
    );
  }
}

class FaviouratePlacesDialog extends StatelessWidget {
  const FaviouratePlacesDialog({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(MapPassengerController());

    return GetBuilder<MapPassengerController>(
      builder: (controller) => Center(
        child: InkWell(
          onTap: () async {
            List favoritePlaces =
                await sql.getAllData(TableName.placesFavorite);

            Get.defaultDialog(
              title: 'Favorite Places'.tr,
              content: SizedBox(
                width: Get.width * .8,
                height: 300,
                child: favoritePlaces.isEmpty
                    ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            const Icon(
                              Icons.star_border_rounded,
                              size: 99,
                              color: AppColor.accentColor,
                            ),
                            Text(
                              'No favorite places yet!'.tr,
                              style: AppStyle.title,
                            ),
                          ],
                        ),
                      )
                    : ListView.separated(
                        itemCount: favoritePlaces.length,
                        separatorBuilder: (context, index) => const Divider(),
                        itemBuilder: (BuildContext context, int index) {
                          return ListTile(
                            leading:
                                const Icon(Icons.star, color: Colors.amber),
                            title: Text(favoritePlaces[index]['name'],
                                style: AppStyle.title),
                            trailing: IconButton(
                              icon: const Icon(Icons.delete_outline,
                                  color: Colors.redAccent),
                              onPressed: () async {
                                await sql.deleteData(TableName.placesFavorite,
                                    favoritePlaces[index]['id']);

                                Get.back();

                                Toast.show(
                                    context,
                                    '${'Deleted'.tr} ${favoritePlaces[index]['name']} from your favorites',
                                    AppColor.redColor);
                              },
                            ),
                            onTap: () async {
                              Get.back();

                              await controller.getLocation();

                              await controller.getDirectionMap(
                                '${controller.passengerLocation.latitude},${controller.passengerLocation.longitude}',
                                '${favoritePlaces[index]['latitude']},${favoritePlaces[index]['longitude']}',
                              );

                              controller.showBottomSheet1();
                            },
                          );
                        },
                      ),
              ),
              confirm: MyElevatedButton(
                  title: 'Back'.tr, onPressed: () => Get.back()),
            );
          },
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.star_border_rounded,
                  color: AppColor.accentColor),
              const SizedBox(width: 8),
              Text('Favorite Places'.tr, style: AppStyle.title),
            ],
          ),
        ),
      ),
    );
  }
}
