import 'dart:convert';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/controller/functions/location_controller.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

import '../../constant/links.dart';
import '../../main.dart';
import '../../print.dart';
import '../../views/widgets/mydialoug.dart';
import '../functions/crud.dart';

class RideAvailableController extends GetxController {
  bool isLoading = false;
  Map rideAvailableMap = {};
  late LatLng southwest;
  late LatLng northeast;

  LatLngBounds calculateBounds(double lat, double lng, double radiusInMeters) {
    const double earthRadius = 6378137.0; // Earth's radius in meters

    double latDelta = (radiusInMeters / earthRadius) * (180 / pi);
    double lngDelta =
        (radiusInMeters / (earthRadius * cos(pi * lat / 180))) * (180 / pi);

    double minLat = lat - latDelta;
    double maxLat = lat + latDelta;

    double minLng = lng - lngDelta;
    double maxLng = lng + lngDelta;

    // Ensure the latitude is between -90 and 90
    minLat = max(-90.0, minLat);
    maxLat = min(90.0, maxLat);

    // Ensure the longitude is between -180 and 180
    minLng = (minLng + 180) % 360 - 180;
    maxLng = (maxLng + 180) % 360 - 180;

    // Ensure the bounds are in the correct order
    if (minLng > maxLng) {
      double temp = minLng;
      minLng = maxLng;
      maxLng = temp;
    }

    return LatLngBounds(
      southwest: LatLng(minLat, minLng),
      northeast: LatLng(maxLat, maxLng),
    );
  }

  double calculateDistance(String startLocation) {
    List<String> startLocationParts = startLocation.split(',');
    double startLatitude = double.parse(startLocationParts[0]);
    double startLongitude = double.parse(startLocationParts[1]);

    // Assuming currentLocation is the driver's location
    double currentLatitude = Get.find<LocationController>().latitude;
    double currentLongitude = Get.find<LocationController>().longitude;

    return Geolocator.distanceBetween(
      currentLatitude,
      currentLongitude,
      startLatitude,
      startLongitude,
    );
  }

  // void sortRidesByDistance() {
  //   rideAvailableMap['message'].sort((a, b) {
  //     double distanceA = calculateDistance(a['start_location']);
  //     double distanceB = calculateDistance(b['start_location']);
  //     return distanceA.compareTo(distanceB);
  //   });
  // }

  getRideAvailable() async {
    try {
      isLoading = true;
      update();

      LatLngBounds bounds = calculateBounds(
          Get.find<LocationController>().myLocation!.latitude,
          Get.find<LocationController>().myLocation!.longitude,
          4000);

      var payload = {
        'southwestLat': bounds.southwest.latitude.toString(),
        'southwestLon': bounds.southwest.longitude.toString(),
        'northeastLat': bounds.northeast.latitude.toString(),
        'northeastLon': bounds.northeast.longitude.toString(),
      };

      var res =
          await CRUD().get(link: AppLink.getRideWaiting, payload: payload);

      if (res != 'failure') {
        rideAvailableMap = jsonDecode(res);
        isLoading = false;
        update();
      } else {
        HapticFeedback.lightImpact();
        Get.dialog(
          CupertinoAlertDialog(
            title: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(
                  CupertinoIcons.car,
                  size: 44,
                  color: CupertinoColors.systemGrey,
                ),
                const SizedBox(height: 12),
                Text(
                  "No Rides Available".tr,
                  style: const TextStyle(
                    fontSize: 17,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
            content: Padding(
              padding: const EdgeInsets.only(top: 8),
              child: Text(
                "Please check back later for available rides.".tr,
                style: const TextStyle(
                  fontSize: 13,
                  color: CupertinoColors.systemGrey,
                ),
              ),
            ),
            actions: [
              CupertinoDialogAction(
                onPressed: () {
                  Get.back();
                  Get.back();
                },
                child: Text('OK'.tr),
              ),
            ],
          ),
          barrierDismissible: true,
          transitionCurve: Curves.easeOutBack,
          transitionDuration: const Duration(milliseconds: 200),
        );
      }
    } catch (e) {
      isLoading = false;
      update();
      Get.dialog(
        CupertinoAlertDialog(
          title: const Icon(
            CupertinoIcons.exclamationmark_triangle_fill,
            color: CupertinoColors.systemRed,
            size: 44,
          ),
          content: Text(
            "Error fetching rides. Please try again.".tr,
            style: const TextStyle(fontSize: 14),
          ),
          actions: [
            CupertinoDialogAction(
              onPressed: () => Get.back(),
              child: Text('OK'.tr),
            ),
          ],
        ),
      );
    }
  }

  @override
  void onInit() {
    getRideAvailable();
    super.onInit();
  }
}
