// ignore_for_file: use_build_context_synchronously

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import '../map_bloc.dart';
import 'show_direction_widget.dart';
import '../../../product/constant/icon/icon_constants.dart';
import '../../../product/extention/context_extention.dart';
import '../../../product/services/language_services.dart';
import '../../../product/services/map_services.dart';
import '../../../product/shared/model/near_by_search_model.dart';

showNearPlacesSideSheet(
  BuildContext context,
  double latitude,
  double longitude,
  String searchKey,
  int radius,
  String type,
  MapBloc mapBloc,
  Completer<GoogleMapController> controller,
  List<Marker> markers,
  BitmapDescriptor hospitalIcon,
  BitmapDescriptor fireStationIcon,
) async {
  double screenWidth = MediaQuery.of(context).size.width;
  double screenHeight = MediaQuery.of(context).size.height;
  LatLng testLocation = LatLng(latitude, longitude);
  List<PlaceDetails> placeDetails = [];
  placeDetails =
      await findLocation(latitude, longitude, searchKey, radius, type);
  await mapBloc.updateCameraPosition(controller, latitude, longitude, 12.0);
  if (placeDetails.isNotEmpty) {
    for (int i = 0; i < placeDetails.length; i++) {
      Marker marker = Marker(
        markerId: MarkerId(placeDetails[i].result!.placeId!),
        position: LatLng(placeDetails[i].result!.geometry!.location!.lat!,
            placeDetails[i].result!.geometry!.location!.lng!),
        infoWindow: InfoWindow(title: placeDetails[i].result!.name!),
        icon:
            searchKey == "Bệnh viện gần nhất" ? hospitalIcon : fireStationIcon,
      );
      markers.add(marker);
    }
  }
  showModalBottomSheet(
    context: context,
    builder: (modalBottomSheetContext) {
      return Container(
        padding: context.paddingLow,
        width: screenWidth,
        height: screenHeight / 3,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Center(
                  child: Text(
                    '${appLocalization(modalBottomSheetContext).map_result}: ',
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Container(
                  alignment: Alignment.centerRight,
                  child: IconButton(
                    onPressed: () async {
                      Navigator.pop(modalBottomSheetContext);
                      markers.clear();
                      await mapBloc.updateCameraPosition(
                        controller,
                        latitude,
                        longitude,
                        14.0,
                      );
                    },
                    icon: IconConstants.instance.getMaterialIcon(Icons.close),
                  ),
                ),
              ],
            ),
            if (placeDetails.isNotEmpty)
              Expanded(
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: placeDetails.length,
                  itemBuilder: (BuildContext listViewContext, int index) {
                    final place = placeDetails[index];
                    return GestureDetector(
                      onTap: () async {
                        await mapBloc.updateCameraPosition(
                          controller,
                          place.result!.geometry!.location!.lat!,
                          place.result!.geometry!.location!.lng!,
                          17.0,
                        );
                      },
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20.0),
                        ),
                        child: Container(
                          padding: listViewContext.paddingLow,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20.0),
                          ),
                          width: screenWidth / 1.5,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                place.result!.name!,
                                style: const TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              SizedBox(height: listViewContext.lowValue),
                              Text(
                                  '${appLocalization(listViewContext).change_profile_address} ${place.result!.formattedAddress} '),
                              SizedBox(height: listViewContext.lowValue),
                              if (place.result?.openingHours?.openNow == null)
                                Text(
                                  appLocalization(listViewContext)
                                      .map_always_opened,
                                  style: const TextStyle(
                                    color: Colors.green,
                                  ),
                                )
                              else
                                place.result?.openingHours?.openNow ?? false
                                    ? Text(
                                        appLocalization(listViewContext)
                                            .map_openning,
                                        style: const TextStyle(
                                          color: Colors.green,
                                        ),
                                      )
                                    : Text(
                                        appLocalization(listViewContext)
                                            .map_closed,
                                        style: const TextStyle(
                                          color: Colors.red,
                                        ),
                                      ),
                              SizedBox(
                                height: listViewContext.lowValue,
                              ),
                              Center(
                                child: ElevatedButton.icon(
                                  style: const ButtonStyle(
                                    backgroundColor:
                                        MaterialStatePropertyAll(Colors.blue),
                                    foregroundColor:
                                        MaterialStatePropertyAll(Colors.white),
                                  ),
                                  onPressed: () async {
                                    Navigator.pop(modalBottomSheetContext);
                                    var destination = LatLng(
                                        place.result!.geometry!.location!.lat!,
                                        place.result!.geometry!.location!.lng!);
                                    mapBloc.findTheWay(context, controller,
                                        testLocation, destination);
                                    // findTheWay(myLocation, destination);
                                    await mapBloc.updateCameraPosition(
                                      controller,
                                      place.result!.geometry!.location!.lat!,
                                      place.result!.geometry!.location!.lng!,
                                      13.0,
                                    );
                                    showDirections(
                                      context,
                                      controller,
                                      markers,
                                      mapBloc,
                                      appLocalization(context)
                                          .map_your_location,
                                      place.result!.name!,
                                      latitude,
                                      longitude,
                                    );
                                  },
                                  icon: IconConstants.instance
                                      .getMaterialIcon(Icons.turn_right),
                                  label: Text(appLocalization(listViewContext)
                                      .map_show_direction),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                ),
              )
            else
              Center(
                child: Text(
                  appLocalization(modalBottomSheetContext).map_no_results,
                ),
              ),
          ],
        ),
      );
    },
  );
}

Future<List<PlaceDetails>> findLocation(double latitude, double longitude,
    String searchKey, int radius, String type) async {
  MapServices mapServices = MapServices();

  final nearByPlaces = await mapServices.getNearbyPlaces(
      latitude, longitude, searchKey, radius, type);

  return nearByPlaces.isNotEmpty ? nearByPlaces : [];
}
