import 'package:SEFER/controller/home/captin/home_captain_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:SEFER/constant/box_name.dart';
import 'package:SEFER/controller/firebase/firbase_messge.dart';
import 'package:SEFER/main.dart';
import 'package:SEFER/views/home/Captin/driver_map_page.dart';
import 'package:SEFER/views/widgets/my_scafold.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'dart:math' as math;
import '../../../../constant/colors.dart';
import '../../../../constant/links.dart';
import '../../../../constant/style.dart';
import '../../../../controller/functions/crud.dart';
import '../../../../controller/functions/launch.dart';
import '../../../../controller/home/captin/order_request_controller.dart';
import '../../../widgets/elevated_btn.dart';

class OrderRequestPage extends StatelessWidget {
  OrderRequestPage({super.key});
  OrderRequestController orderRequestController =
      Get.put(OrderRequestController());
  @override
  Widget build(BuildContext context) {
    final arguments = Get.arguments;
    final myListString = arguments['myListString'];
    final myList = arguments['DriverList'];
    // final pointsList = arguments['PolylineJson'];
    final body = arguments['body'];
    Duration durationToAdd = Duration(seconds: int.parse(myList[4]));
    int hours = durationToAdd.inHours;
    int minutes = (durationToAdd.inMinutes % 60).round();
    orderRequestController.startTimer(myList[6].toString(), body.toString());
    var coords = myList[0].split(',');
    var coordDestination = myList[1].split(',');
    BitmapDescriptor startIcon = BitmapDescriptor.defaultMarker;
    BitmapDescriptor endIcon = BitmapDescriptor.defaultMarker;

// Parse to double
    double latPassengerLocation = double.parse(coords[0]);
    double lngPassengerLocation = double.parse(coords[1]);
    double latPassengerDestination = double.parse(coordDestination[0]);
    double lngPassengerDestination = double.parse(coordDestination[1]);

    List<LatLng> pointsDirection = [
      LatLng(latPassengerLocation, lngPassengerLocation),
      LatLng(latPassengerDestination, lngPassengerDestination)
    ]; // Calculate the midpoint between the two points
    // Calculate the minimum and maximum latitude and longitude values
    double minLatitude =
        math.min(pointsDirection[0].latitude, pointsDirection[1].latitude);
    double maxLatitude =
        math.max(pointsDirection[0].latitude, pointsDirection[1].latitude);
    double minLongitude =
        math.min(pointsDirection[0].longitude, pointsDirection[1].longitude);
    double maxLongitude =
        math.max(pointsDirection[0].longitude, pointsDirection[1].longitude);
// Create a bounding box using the calculated values
    LatLngBounds bounds = LatLngBounds(
      southwest: LatLng(minLatitude, minLongitude),
      northeast: LatLng(maxLatitude, maxLongitude),
    );
    // void addCustomStartIcon() async {
// Create the marker with the resized image
    orderRequestController.calculateConsumptionFuel();

    ImageConfiguration config = ImageConfiguration(
        size: const Size(25, 25), devicePixelRatio: Get.pixelRatio);
    BitmapDescriptor.fromAssetImage(config, 'assets/images/A.png',
            mipmaps: false)
        .then((value) {
      startIcon = value;
    });
    ImageConfiguration config1 = ImageConfiguration(
        size: const Size(25, 25), devicePixelRatio: Get.pixelRatio);
    BitmapDescriptor.fromAssetImage(config1, 'assets/images/b.png',
            mipmaps: false)
        .then((value) {
      endIcon = value;
    });
    // }
    // orderRequestController.calculateConsumptionFuel();

    return MyScafolld(
        title: 'Order Details'.tr,
        body: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 6),
            child: ListView(
              // crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // SizedBox(height: 200, child: Text(pointsList.toString())),
                // Text(message.notification!.body.toString()),
                SizedBox(
                  height: Get.height * .2,
                  child: GoogleMap(
                    initialCameraPosition: CameraPosition(
                        zoom: 12,
                        target: Get.find<HomeCaptainController>().myLocation),
                    cameraTargetBounds: CameraTargetBounds(bounds),
                    myLocationButtonEnabled: true,
                    trafficEnabled: true,
                    buildingsEnabled: true,
                    mapToolbarEnabled: true,
                    myLocationEnabled: true,
                    markers: {
                      Marker(
                          markerId: MarkerId('MyLocation'.tr),
                          position: LatLng(
                              latPassengerLocation, lngPassengerLocation),
                          draggable: true,
                          icon: startIcon),
                      Marker(
                          markerId: MarkerId('Destination'.tr),
                          position: LatLng(
                              latPassengerDestination, lngPassengerDestination),
                          draggable: true,
                          icon: endIcon),
                    },
                    polylines: {
                      Polyline(
                        zIndex: 1,
                        consumeTapEvents: true,
                        geodesic: true,
                        endCap: Cap.buttCap,
                        startCap: Cap.buttCap,
                        visible: true,
                        polylineId: const PolylineId('routeOrder'),
                        points: pointsDirection,
                        color: AppColor.primaryColor,
                        width: 2,
                      ),
                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Card(
                    elevation: 3,
                    color: myList[20].toString() == 'haveSteps'
                        ? AppColor.greenColor
                        : AppColor.secondaryColor,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        TextButton.icon(
                            onPressed: () {
                              String mapUrl =
                                  'https://www.google.com/maps/dir/${myList[0]}/${myList[1]}/';
                              print(mapUrl);
                              showInBrowser(mapUrl);
                            },
                            icon: const Icon(Icons.map),
                            label: myList[20].toString() == 'haveSteps'
                                ? Text(
                                    'Trip has Steps'.tr,
                                    style: AppStyle.title,
                                  )
                                : Text('Rouats of Trip'.tr,
                                    style: AppStyle.title)),
                        Container(
                          color: myList[13].toString() == 'true'
                              ? AppColor.deepPurpleAccent
                              : AppColor.greenColor,
                          child: myList[13].toString() ==
                                  'true' //Visa or Cash Method from notify to driver
                              ? Text(
                                  'Visa',
                                  style: AppStyle.title,
                                )
                              : Text('Cash', style: AppStyle.title),
                        )
                      ],
                    ),
                  ),
                ),

                Container(
                  decoration: AppStyle.boxDecoration1,
                  child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Text(
                            double.parse(myList[2]).toStringAsFixed(2),
                            style: AppStyle.headTitle2,
                          ),
                          Text(
                            myList[31].toString(),
                            style: AppStyle.title
                                .copyWith(color: AppColor.greenColor),
                          ),
                        ],
                      )),
                ),
                Container(
                  height: Get.height * .2,
                  width: Get.width * .9,
                  decoration: AppStyle.boxDecoration1,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              const Icon(
                                Icons.arrow_circle_up,
                                color: AppColor.greenColor,
                              ),
                              Text(
                                myList[12] + ' ' + ' (${myList[11]}) ',
                                style: AppStyle.title,
                              ),
                            ],
                          ),
                          Text(
                            myList[29],
                            style: AppStyle.title,
                          ),
                        ],
                      ),
                      Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              const Icon(
                                Icons.arrow_circle_up,
                                color: AppColor.greenColor,
                              ),
                              Text(
                                myList[5] + ' ' + ' (${myList[4]}) ',
                                style: AppStyle.title,
                              ),
                            ],
                          ),
                          Text(
                            myList[30],
                            style: AppStyle.title,
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: RichText(
                    text: TextSpan(
                      text: 'Passenger name : '
                          .tr, // Changed text to be more generic
                      style: AppStyle.subtitle,
                      children: [
                        TextSpan(
                            text: myList[8],
                            style: AppStyle
                                .title), // Assuming myList[8] holds passenger name
                        TextSpan(text: ' (', style: AppStyle.subtitle),
                        TextSpan(
                            text: myList[33].toString(),
                            style: AppStyle
                                .title), // Assuming 'rate' holds the passenger rate
                        TextSpan(text: ' ⭐)', style: AppStyle.subtitle),
                      ],
                    ),
                  ),
                ),

                Padding(
                  padding: const EdgeInsets.all(4),
                  child: Container(
                    color: AppColor.deepPurpleAccent,
                    child: RichText(
                      text: TextSpan(
                        text: 'Cost Of Trip IS '.tr,
                        style: AppStyle.title,
                        children: [
                          TextSpan(
                              text: myList[27], style: AppStyle.headTitle2),
                        ],
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      MyElevatedButton(
                        kolor: AppColor.greenColor,
                        title: 'Accept Order'.tr,
                        onPressed: () async {
                          box.write(BoxName.statusDriverLocation, 'on');

                          orderRequestController.changeApplied();
                          await CRUD().postFromDialogue(
                              link: AppLink.addDriverOrder,
                              payload: {
                                'driver_id': myList[6].toString(),
                                // box.read(BoxName.driverID).toString(),
                                'order_id': body.toString(),
                                'status': 'Apply'
                              });
                          await CRUD()
                              .post(link: AppLink.updateRides, payload: {
                            'id': myList[16],
                            'rideTimeStart': DateTime.now().toString(),
                            'status': 'Apply',
                            'driver_id': box.read(BoxName.driverID),
                          });
                          // Get.back();
                          List<String> bodyToPassenger = [
                            box.read(BoxName.driverID).toString(),
                            box.read(BoxName.nameDriver).toString(),
                            box.read(BoxName.tokenDriver).toString(),
                          ];
                          // print(bodyToPassenger);
                          FirebaseMessagesController()
                              .sendNotificationToPassengerToken(
                            'Apply Ride', 'your ride is applied'.tr,
                            // arguments['DriverList'][9].toString(),
                            arguments['DriverList'][9].toString(),
                            // box.read(BoxName.tokenDriver).toString(),
                            bodyToPassenger,
                          );
                          Get.back();
                          Get.to(() => PassengerLocationMapPage(), arguments: {
                            'passengerLocation': myList[0].toString(),
                            'passengerDestination': myList[1].toString(),
                            'Duration': myList[4].toString(),
                            'totalCost': myList[26].toString(),
                            'Distance': myList[5].toString(),
                            'name': myList[8].toString(),
                            'phone': myList[10].toString(),
                            'email': myList[28].toString(),
                            'WalletChecked': myList[13].toString(),
                            'tokenPassenger': myList[9].toString(),
                            'direction':
                                'https://www.google.com/maps/dir/${myList[0]}/${myList[1]}/',
                            'DurationToPassenger': myList[15].toString(),
                            'rideId': myList[16].toString(),
                            'passengerId': myList[7].toString(),
                            'driverId': myList[18].toString(),
                            'durationOfRideValue': myList[19].toString(),
                            'paymentAmount': myList[2].toString(),
                            'paymentMethod': myList[13].toString() == 'true'
                                ? 'visa'
                                : 'cash',
                            'isHaveSteps': myList[20].toString(),
                            'step0': myList[21].toString(),
                            'step1': myList[22].toString(),
                            'step2': myList[23].toString(),
                            'step3': myList[24].toString(),
                            'step4': myList[25].toString(),
                            'passengerWalletBurc': myList[26].toString(),
                            'timeOfOrder': DateTime.now().toString(),
                            'totalPassenger': myList[2].toString(),
                            'carType': myList[31].toString(),
                            'kazan': myList[32].toString(),
                          });
                        },
                      ),
                      GetBuilder<OrderRequestController>(
                        builder: (timerController) {
                          final isNearEnd = timerController.remainingTime <=
                              5; // Define a threshold for "near end"

                          return Stack(
                            alignment: Alignment.center,
                            children: [
                              CircularProgressIndicator(
                                value: timerController.progress,
                                // Set the color based on the "isNearEnd" condition
                                color: isNearEnd ? Colors.red : Colors.blue,
                              ),
                              Text(
                                '${timerController.remainingTime}',
                                style: AppStyle.number,
                              ),
                            ],
                          );
                        },
                      ),
                      MyElevatedButton(
                        title: 'Refuse Order'.tr,
                        onPressed: () async {
                          List<String> bodyToPassenger = [
                            box.read(BoxName.driverID).toString(),
                            box.read(BoxName.nameDriver).toString(),
                            box.read(BoxName.tokenDriver).toString(),
                          ];

                          FirebaseMessagesController()
                              .sendNotificationToPassengerToken(
                            'Refused Ride',
                            '${box.read(BoxName.nameDriver)} ${'reject your order.'.tr}',
                            arguments['DriverList'][9].toString(),
                            // box.read(BoxName.tokenDriver).toString(),
                            bodyToPassenger,
                          );
                          orderRequestController.refuseOrder(
                            myList[16].toString(),
                          );
                          orderRequestController.addRideToNotificationDriverString(
                              myList[16].toString(),
                              myList[29].toString(),
                              myList[30].toString(),
                              '${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day}',
                              '${DateTime.now().hour}:${DateTime.now().minute}',
                              myList[2].toString(),
                              myList[7].toString(),
                              'wait',
                              myList[31].toString(),
                              myList[33].toString(),
                              myList[2].toString(),
                              myList[5].toString(),
                              myList[4].toString()); //duration
                        },
                        kolor: AppColor.redColor,
                      ),
                    ],
                  ),
                )
              ],
            ),
          )
        ],
        isleading: true);
  }
}
