import 'dart:convert';

import 'package:sefer_driver/controller/home/captin/home_captain_controller.dart';
import 'package:sefer_driver/views/widgets/mydialoug.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/controller/firebase/firbase_messge.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/home/Captin/driver_map_page.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/encrypt_decrypt.dart';
import '../../../../controller/functions/launch.dart';
import '../../../../controller/home/captin/order_request_controller.dart';
import '../../../widgets/elevated_btn.dart';

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

  @override
  State<OrderRequestPage> createState() => _OrderRequestPageState();
}

class _OrderRequestPageState extends State<OrderRequestPage> {
  final OrderRequestController orderRequestController =
      Get.put(OrderRequestController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Order Request'.tr),
        centerTitle: true,
      ),
      body: GetBuilder<OrderRequestController>(
        builder: (controller) {
          if (controller.myList == null) {
            return const Center(child: CircularProgressIndicator());
          }
          return Column(
            children: [
              SizedBox(
                height: Get.height * 0.3,
                child: GoogleMap(
                  mapType: MapType.normal,
                  initialCameraPosition: CameraPosition(
                    target: LatLng(controller.latPassengerLocation,
                        controller.lngPassengerLocation),
                    zoom: 14.0,
                  ),
                  myLocationButtonEnabled: true,
                  onMapCreated: controller.onMapCreated,
                  myLocationEnabled: true,
                  markers: {
                    Marker(
                      markerId: const MarkerId('startLocation'),
                      position: LatLng(controller.latPassengerLocation,
                          controller.lngPassengerLocation),
                      icon: controller.startIcon,
                    ),
                    Marker(
                      markerId: const MarkerId('destinationLocation'),
                      position: LatLng(controller.latPassengerDestination,
                          controller.lngPassengerDestination),
                      icon: controller.endIcon,
                    ),
                  },
                  polylines: {
                    Polyline(
                      polylineId: const PolylineId('route'),
                      color: AppColor.primaryColor,
                      width: 5,
                      points: controller.pointsDirection,
                    ),
                  },
                ),
              ),
              Expanded(
                child: ListView(
                  padding: const EdgeInsets.all(16),
                  children: [
                    Card(
                      elevation: 4,
                      child: ListTile(
                        leading: Icon(
                          controller.myList[13].toString() == 'true'
                              ? Icons.credit_card
                              : Icons.money,
                          color: controller.myList[13].toString() == 'true'
                              ? AppColor.deepPurpleAccent
                              : AppColor.greenColor,
                        ),
                        title: Text(
                          'Payment Method'.tr,
                          style: Theme.of(context).textTheme.titleMedium,
                        ),
                        trailing: Text(
                          controller.myList[13].toString() == 'true'
                              ? 'Visa'
                              : 'Cash',
                          style:
                              Theme.of(context).textTheme.titleMedium?.copyWith(
                                    fontWeight: FontWeight.bold,
                                  ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 10),
                    Card(
                      elevation: 4,
                      child: ListTile(
                        leading: const Icon(Icons.account_circle,
                            color: AppColor.secondaryColor),
                        title: Text(
                          controller.myList[8],
                          style: Theme.of(context).textTheme.titleMedium,
                        ),
                        subtitle: Row(
                          children: [
                            const Icon(Icons.star,
                                size: 16, color: Colors.amber),
                            Text(
                              controller.myList[33].toString(),
                              style: const TextStyle(color: Colors.amber),
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 10),
                    Card(
                      elevation: 4,
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                const Icon(Icons.location_on,
                                    color: AppColor.greenColor),
                                const SizedBox(width: 8),
                                Expanded(
                                  // Keep Expanded here for layout
                                  child: Text(
                                    controller.myList[29],
                                    style:
                                        Theme.of(context).textTheme.titleSmall,
                                    maxLines: 2, // Allow up to 2 lines
                                    overflow: TextOverflow
                                        .ellipsis, // Handle overflow
                                  ),
                                ),
                              ],
                            ),
                            const Divider(),
                            Row(
                              children: [
                                const Icon(Icons.flag,
                                    color: AppColor.redColor),
                                const SizedBox(width: 8),
                                Expanded(
                                  // Keep Expanded here for layout
                                  child: Text(
                                    controller.myList[30],
                                    style:
                                        Theme.of(context).textTheme.titleSmall,
                                    maxLines: 2, // Allow up to 2 lines
                                    overflow: TextOverflow
                                        .ellipsis, // Handle overflow
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 10),
                    Card(
                      elevation: 4,
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            _InfoTile(
                              icon: Icons.timer,
                              label:
                                  '${(double.parse(controller.myList[12]) / 60).toStringAsFixed(0)} ${'min'.tr}',
                            ),
                            _InfoTile(
                              icon: Icons.directions_car,
                              label:
                                  '${(double.parse(controller.myList[11]) / 1000).toStringAsFixed(1)} ${'km'.tr}',
                            ),
                            _InfoTile(
                              icon: Icons.monetization_on,
                              label: '${controller.myList[2]}',
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 20),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        MyElevatedButton(
                          kolor: AppColor.greenColor,
                          title: 'Accept Order'.tr,
                          onPressed: () async {
                            Get.put(HomeCaptainController()).changeRideId();
                            box.write(BoxName.statusDriverLocation, 'on');
                            controller.endTimer();
                            controller.changeApplied();

                            var res = await CRUD().post(
                                link: AppLink.updateStausFromSpeed,
                                payload: {
                                  'id': (controller.myList[16]),
                                  'rideTimeStart': DateTime.now().toString(),
                                  'status': 'Apply',
                                  'driver_id': box.read(BoxName.driverID),
                                });
                            if (AppLink.endPoint != AppLink.seferCairoServer) {
                              CRUD().post(
                                  link:
                                      "${AppLink.endPoint}/ride/rides/updateStausFromSpeed.php",
                                  payload: {
                                    'id': (controller.myList[16]),
                                    'rideTimeStart': DateTime.now().toString(),
                                    'status': 'Apply',
                                    'driver_id': box.read(BoxName.driverID),
                                  });
                            }
                            if (res == 'failure') {
                              MyDialog().getDialog(
                                  "This ride is already applied by another driver."
                                      .tr,
                                  '', () {
                                Get.back();
                              });
                            } else {
                              await CRUD().postFromDialogue(
                                  link: AppLink.addDriverOrder,
                                  payload: {
                                    'driver_id':
                                        (controller.myList[6].toString()),
                                    'order_id':
                                        (controller.myList[16].toString()),
                                    'status': 'Apply'
                                  });
                              if (AppLink.endPoint !=
                                  AppLink.seferCairoServer) {
                                CRUD().postFromDialogue(
                                    link:
                                        '${AppLink.endPoint}/rides/driver_order/add.php',
                                    payload: {
                                      'driver_id':
                                          (controller.myList[6].toString()),
                                      'order_id':
                                          (controller.myList[16].toString()),
                                      'status': 'Apply'
                                    });
                              }
                              List<String> bodyToPassenger = [
                                controller.myList[6].toString(),
                                controller.myList[8].toString(),
                                controller.myList[9].toString(),
                              ];
                              final fmc =
                                  Get.isRegistered<FirebaseMessagesController>()
                                      ? Get.find<FirebaseMessagesController>()
                                      : Get.put(FirebaseMessagesController());

                              fmc.sendNotificationToDriverMAP(
                                "Accepted Ride",
                                'your ride is Accepted'.tr,
                                controller.myList[9].toString(),
                                bodyToPassenger,
                                'start.wav',
                              );
                              Get.back();
                              box.write(BoxName.rideArguments, {
                                'passengerLocation':
                                    controller.myList[0].toString(),
                                'passengerDestination':
                                    controller.myList[1].toString(),
                                'Duration': controller.myList[4].toString(),
                                'totalCost': controller.myList[26].toString(),
                                'Distance': controller.myList[5].toString(),
                                'name': controller.myList[8].toString(),
                                'phone': controller.myList[10].toString(),
                                'email': controller.myList[28].toString(),
                                'WalletChecked':
                                    controller.myList[13].toString(),
                                'tokenPassenger':
                                    controller.myList[9].toString(),
                                'direction':
                                    'https://www.google.com/maps/dir/${controller.myList[0]}/${controller.myList[1]}/',
                                'DurationToPassenger':
                                    controller.myList[15].toString(),
                                'rideId': (controller.myList[16].toString()),
                                'passengerId':
                                    (controller.myList[7].toString()),
                                'driverId': (controller.myList[18].toString()),
                                'durationOfRideValue':
                                    controller.myList[19].toString(),
                                'paymentAmount':
                                    controller.myList[2].toString(),
                                'paymentMethod':
                                    controller.myList[13].toString() == 'true'
                                        ? 'visa'
                                        : 'cash',
                                'isHaveSteps': controller.myList[20].toString(),
                                'step0': controller.myList[21].toString(),
                                'step1': controller.myList[22].toString(),
                                'step2': controller.myList[23].toString(),
                                'step3': controller.myList[24].toString(),
                                'step4': controller.myList[25].toString(),
                                'passengerWalletBurc':
                                    controller.myList[26].toString(),
                                'timeOfOrder': DateTime.now().toString(),
                                'totalPassenger':
                                    controller.myList[2].toString(),
                                'carType': controller.myList[31].toString(),
                                'kazan': controller.myList[32].toString(),
                                'startNameLocation':
                                    controller.myList[29].toString(),
                                'endNameLocation':
                                    controller.myList[30].toString(),
                              });
                              Get.to(() => PassengerLocationMapPage(),
                                  arguments: box.read(BoxName.rideArguments));
                            }
                          },
                        ),
                        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 {
                            controller.endTimer();
                            List<String> bodyToPassenger = [
                              box.read(BoxName.driverID).toString(),
                              box.read(BoxName.nameDriver).toString(),
                              box.read(BoxName.tokenDriver).toString(),
                            ];

                            FirebaseMessagesController()
                                .sendNotificationToPassengerToken(
                                    'Order Under Review'.tr,
                                    '${box.read(BoxName.nameDriver)} ${'is reviewing your order. They may need more information or a higher price.'.tr}',
                                    controller.myList[9].toString(),
                                    bodyToPassenger,
                                    'notification.wav');

                            controller.refuseOrder(
                              EncryptionHelper.instance.encryptData(
                                  controller.myList[16].toString()),
                            );
                            controller.addRideToNotificationDriverString(
                                controller.myList[16].toString(),
                                controller.myList[29].toString(),
                                controller.myList[30].toString(),
                                '${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day}',
                                '${DateTime.now().hour}:${DateTime.now().minute}',
                                controller.myList[2].toString(),
                                controller.myList[7].toString(),
                                'wait',
                                controller.myList[31].toString(),
                                controller.myList[33].toString(),
                                controller.myList[2].toString(),
                                controller.myList[5].toString(),
                                controller.myList[4].toString());
                          },
                          kolor: AppColor.redColor,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

class _InfoTile extends StatelessWidget {
  final IconData icon;
  final String label;

  const _InfoTile({required this.icon, required this.label});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Icon(icon, color: AppColor.primaryColor),
        const SizedBox(height: 4),
        Text(
          label,
          style: Theme.of(context).textTheme.bodyMedium,
        ),
      ],
    );
  }
}
