import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intaleq_maps/intaleq_maps.dart';
import 'package:siro_driver/constant/api_key.dart';
import 'dart:math' as math;

import '../../../../constant/colors.dart';
import '../../../../controller/home/captin/home_captain_controller.dart';

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

  @override
  State<OrderRequestPageTest> createState() => _OrderRequestPageTestState();
}

class _OrderRequestPageTestState extends State<OrderRequestPageTest> {
  late OrderRequestController _orderRequestController;

  @override
  void initState() {
    super.initState();
    // Initialize the controller and process arguments
    _initializeController();
  }

  void _initializeController() {
    // Get the controller or create a new one if not exists
    _orderRequestController = Get.put(OrderRequestController());

    // Process arguments passed to the page
    final arguments = Get.arguments;
    final myListString = arguments['myListString'];
    var myList =
        arguments['DriverList'] == null || arguments['DriverList'].isEmpty
            ? jsonDecode(myListString)
            : arguments['DriverList'];

    // Parse coordinates and prepare map data
    _orderRequestController.parseCoordinates(myList);

    // Start timer and calculate fuel consumption
    _orderRequestController.startTimer(
      myList[6].toString(),
      myList[16].toString(),
    );
    _orderRequestController.calculateConsumptionFuel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 6),
            child: Container(
              color: const Color.fromARGB(255, 241, 238, 238),
              child: ListView(
                children: [
                  SizedBox(
                    height: Get.height * .33,
                    child: Obx(() => IntaleqMap(
                          apiKey: AK.mapAPIKEY,
                          initialCameraPosition: CameraPosition(
                            zoom: 12,
                            target:
                                Get.find<HomeCaptainController>().myLocation,
                          ),
                          cameraTargetBounds: CameraTargetBounds(
                              _orderRequestController.mapBounds.value),
                          myLocationButtonEnabled: true,
                          // trafficEnabled: false,
                          // buildingsEnabled: false,
                          // mapToolbarEnabled: true,
                          myLocationEnabled: true,
                          markers: _orderRequestController.markers.value,
                          polylines: _orderRequestController.polylines.value,
                          onMapCreated: (IntaleqMapController controller) {
                            _orderRequestController.mapController.value =
                                controller;
                          },
                          onCameraMove: (CameraPosition position) {
                            _orderRequestController
                                .updateCameraPosition(position);
                          },
                        )),
                  ),
                  // Rest of your UI components
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class OrderRequestController extends GetxController {
  // Reactive variables for map-related data
  Rx<LatLngBounds> mapBounds = Rx<LatLngBounds>(LatLngBounds(
      southwest: const LatLng(0, 0), northeast: const LatLng(0, 0)));

  Rx<Set<Marker>> markers = Rx<Set<Marker>>({});
  Rx<Set<Polyline>> polylines = Rx<Set<Polyline>>({});

  Rx<IntaleqMapController?> mapController = Rx<IntaleqMapController?>(null);

  // Icons for start and end markers
  late InlqBitmap startIcon;
  late InlqBitmap endIcon;

  // Coordinates for passenger location and destination
  Rx<LatLng?> passengerLocation = Rx<LatLng?>(null);
  Rx<LatLng?> passengerDestination = Rx<LatLng?>(null);

  @override
  void onInit() {
    super.onInit();
    // Initialize marker icons
    _initializeMarkerIcons();
  }

  void _initializeMarkerIcons() async {
    // Load custom marker icons
    startIcon = InlqBitmap.fromAsset('assets/start_marker.png');
    endIcon = InlqBitmap.fromAsset('assets/end_marker.png');
  }

  void parseCoordinates(List myList) {
    // Parse coordinates from the input list
    var cords = myList[0].split(',');
    var cordDestination = myList[1].split(',');

    double latPassengerLocation = double.parse(cords[0]);
    double lngPassengerLocation = double.parse(cords[1]);
    double latPassengerDestination = double.parse(cordDestination[0]);
    double lngPassengerDestination = double.parse(cordDestination[1]);

    // Update passenger location and destination
    passengerLocation.value =
        LatLng(latPassengerLocation, lngPassengerLocation);
    passengerDestination.value =
        LatLng(latPassengerDestination, lngPassengerDestination);

    // Create markers
    _createMarkers();

    // Create polyline
    _createPolyline();

    // Calculate map bounds
    _calculateMapBounds();
  }

  void _createMarkers() {
    if (passengerLocation.value == null || passengerDestination.value == null)
      return;

    markers.value = {
      Marker(
        markerId: MarkerId('MyLocation'.tr),
        position: passengerLocation.value!,
        draggable: true,
        icon: startIcon,
      ),
      Marker(
        markerId: MarkerId('Destination'.tr),
        position: passengerDestination.value!,
        draggable: true,
        icon: endIcon,
      ),
    };
  }

  void _createPolyline() {
    if (passengerLocation.value == null || passengerDestination.value == null)
      return;

    polylines.value = {
      Polyline(
        zIndex: 1,
        // consumeTapEvents: true,
        geodesic: true,
        // endCap: Cap.buttCap,
        // startCap: Cap.buttCap,
        visible: true,
        polylineId: const PolylineId('routeOrder'),
        points: [passengerLocation.value!, passengerDestination.value!],
        color: AppColor.primaryColor,
        width: 2,
      ),
    };
  }

  void _calculateMapBounds() {
    if (passengerLocation.value == null || passengerDestination.value == null)
      return;

    double minLatitude = math.min(passengerLocation.value!.latitude,
        passengerDestination.value!.latitude);
    double maxLatitude = math.max(passengerLocation.value!.latitude,
        passengerDestination.value!.latitude);
    double minLongitude = math.min(passengerLocation.value!.longitude,
        passengerDestination.value!.longitude);
    double maxLongitude = math.max(passengerLocation.value!.longitude,
        passengerDestination.value!.longitude);

    mapBounds.value = LatLngBounds(
      southwest: LatLng(minLatitude, minLongitude),
      northeast: LatLng(maxLatitude, maxLongitude),
    );
  }

  void updateCameraPosition(CameraPosition position) {
    // Implement any specific logic for camera position updates
  }

  void startTimer(String param1, String param2) {
    // Implement timer start logic
  }

  void calculateConsumptionFuel() {
    // Implement fuel consumption calculation
  }
}
