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 '../../../../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 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());
    return MyScafolld(
        title: 'Order Request Page'.tr,
        body: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Text(message.notification!.body.toString()),
              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),
                      )
                    ],
                  ),
                ),
              ),

              Padding(
                padding: const EdgeInsets.all(8.0),
                child: RichText(
                  text: TextSpan(
                    text: 'Passenger Name is '.tr,
                    style: AppStyle.title,
                    children: [
                      TextSpan(text: myList[8], style: AppStyle.headTitle2),
                    ],
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: RichText(
                  text: TextSpan(
                    text: 'Total From Passenger is '.tr,
                    style: AppStyle.title,
                    children: [
                      TextSpan(
                          text: double.parse(myList[2]).toStringAsFixed(2),
                          style: AppStyle.headTitle2),
                    ],
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: RichText(
                  text: TextSpan(
                    text: 'Duration To Passenger is '.tr,
                    style: AppStyle.title,
                    children: [
                      TextSpan(
                          text: myList[11].toString(),
                          style: AppStyle.headTitle2),
                    ],
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: RichText(
                  text: TextSpan(
                    text: 'Distance To Passenger is '.tr,
                    style: AppStyle.title,
                    children: [
                      TextSpan(
                          text: myList[12].toString(),
                          style: AppStyle.headTitle2),
                    ],
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Container(
                  color: AppColor.deepPurpleAccent,
                  child: RichText(
                    text: TextSpan(
                      text: 'Cost Of Trip IS '.tr,
                      style: AppStyle.title,
                      children: [
                        TextSpan(
                            text: double.parse(myList[26]).toStringAsFixed(2),
                            style: AppStyle.headTitle2),
                      ],
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: RichText(
                  text: TextSpan(
                      text: 'Distance from Passenger to destination is '.tr,
                      style: AppStyle.title,
                      children: [
                        TextSpan(
                            text: myList[5].toString(),
                            style: AppStyle.headTitle2),
                        TextSpan(text: ' KM'.tr, style: AppStyle.title),
                      ]),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: RichText(
                  text: TextSpan(
                      text: 'Duration of Trip is '.tr,
                      style: AppStyle.title,
                      children: [
                        TextSpan(
                            text: hours > 1
                                ? '${'Your Ride Duration is '.tr}$hours${' H and'.tr} $minutes m'
                                : '${'Your Ride Duration is '.tr} $minutes m',
                            style: AppStyle.title),
                        TextSpan(text: ' Minutes'.tr, style: AppStyle.title),
                      ]),
                ),
              ),
              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'
                        });
                        // 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',
                          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(),
                        });
                      },
                    ),
                    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)} ${'rejct your order.'.tr}',
                          arguments['DriverList'][9].toString(),
                          // box.read(BoxName.tokenDriver).toString(),
                          bodyToPassenger,
                        );
                        orderRequestController.refuseOrder(
                            myList[16].toString(), body.toString());
                      },
                      kolor: AppColor.redColor,
                    ),
                  ],
                ),
              )
            ],
          )
        ],
        isleading: true);
  }
}
