import 'package:SEFER/views/home/profile/feed_back_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:get/get.dart';
import 'package:SEFER/constant/box_name.dart';
import 'package:SEFER/controller/profile/profile_controller.dart';
import 'package:SEFER/main.dart';

import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/home/map_passenger_controller.dart';

class RideBeginPassenger extends StatelessWidget {
  const RideBeginPassenger({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    ProfileController profileController = Get.put(ProfileController());
    return GetBuilder<MapPassengerController>(builder: (controller) {
      if (controller.rideTimerBegin) {
        return Positioned(
          left: 10,
          right: 10,
          bottom: 4,
          child: Container(
            decoration: AppStyle.boxDecoration,
            height: controller.rideTimerBegin ? 200 : 0,
            // width: 100,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Column(
                        children: [
                          Text(
                            // 'You will arrive to your destination after timer end.'.tr,
                            'Time to arrive'.tr,
                            style: AppStyle.title,
                          ),
                          Text(
                            controller.arrivalTime,
                            style: AppStyle.title,
                          ),
                        ],
                      ),
                      Column(
                        children: [
                          Text(
                            'Total Cost'.tr,
                            style: AppStyle.title,
                          ),
                          Text(
                            controller.totalPassenger.toStringAsFixed(2),
                            style: AppStyle.title,
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Column(
                            children: [
                              Text('Write note'.tr),
                              IconButton(
                                onPressed: () {
                                  Get.to(
                                    () => FeedBackPage(),
                                    transition: Transition.downToUp,
                                  );
                                },
                                icon: const Icon(
                                  Icons.note_add,
                                  color: AppColor.redColor,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ],
                  ),
                  Stack(
                    children: [
                      // StreamCounter(),
                      LinearProgressIndicator(
                        backgroundColor: AppColor.accentColor,
                        color: controller.remainingTimeTimerRideBegin < 60
                            ? AppColor.redColor
                            : AppColor.greenColor,
                        minHeight: 25,
                        borderRadius: BorderRadius.circular(15),
                        value: controller.progressTimerRideBegin.toDouble(),
                      ),
                      Center(
                        child: Text(
                          controller.stringRemainingTimeRideBegin,
                          style: AppStyle.title,
                        ),
                      )
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      IconButton(
                        onPressed: () async {
                          if (box.read(BoxName.sosPhonePassenger) == null) {
                            {
                              await profileController.updatField(
                                  'sosPhone', TextInputType.phone);
                              box.write(BoxName.sosPhonePassenger,
                                  profileController.prfoileData['sosPhone']);
                            }
                            // Get.defaultDialog(
                            //     title: 'You dont Add Emergency Phone Yet!'.tr,
                            //     content: Column(
                            //       children: [
                            //         Form(
                            //           key: controller.sosFormKey,
                            //           child: TextFormField(
                            //             keyboardType: TextInputType
                            //                 .phone, // Set the keyboard type to phone
                            //             controller:
                            //                 controller.sosPhonePassengerProfile,
                            //             validator: (value) {
                            //               if (value!.isEmpty ||
                            //                   value.length != 10) {
                            //                 return 'Please enter a valid phone number'
                            //                     .tr;
                            //               }
                            //               // Add additional validation if needed
                            //               return null;
                            //             },
                            //             decoration: const InputDecoration(
                            //               border: OutlineInputBorder(),
                            //               hintText: 'Type here',
                            //             ),
                            //           ),
                            //         )
                            //       ],
                            //     ),
                            //     confirm: MyElevatedButton(
                            //         title: 'Add Phone'.tr,
                            //         onPressed: () async {
                            //           await profileController
                            //               .updatField('sosPhone');
                            //           box.write(
                            //               BoxName.sosPhonePassenger,
                            //               profileController
                            //                   .prfoileData['sosPhone']);
                            //         }));
                          } else {
                            controller
                                .sendSMS(box.read(BoxName.sosPhonePassenger));
                          }
                        },
                        icon: const Icon(
                          Icons.sos_rounded,
                          color: AppColor.redColor,
                        ),
                      ),
                      IconButton(
                        onPressed: () async {
                          print(box.read(BoxName.sosPhonePassenger));
                          if (box.read(BoxName.sosPhonePassenger) == null ||
                              box.read(BoxName.sosPhonePassenger) == 'sos') {
                            {
                              await profileController.updatField(
                                  'sosPhone', TextInputType.phone);
                              box.write(BoxName.sosPhonePassenger,
                                  profileController.prfoileData['sosPhone']);
                            }
                          } else {
                            String phoneNumber =
                                box.read(BoxName.sosPhonePassenger).toString();
                            phoneNumber = phoneNumber.replaceAll('0', '');
                            print(phoneNumber); // Output: 798583061
                            var phone =
                                '+${box.read(BoxName.countryCode)}${box.read(BoxName.sosPhonePassenger)}';
                            controller.sendWhatsapp(phone);
                          }
                        },
                        icon: const Icon(
                          FontAwesome.whatsapp,
                          color: AppColor.greenColor,
                        ),
                      ),
                    ],
                  )
                  // controller.remainingTimeTimerRideBegin < 5
                  //     ? MyElevatedButton(
                  //         title:
                  //             'If you in destination Now. Press finish The Ride',
                  //         onPressed: () async {
                  //todo finish the trip and rest all counter ,start new counter of the trip time

                  // await CRUD()
                  //     .post(link: AppLink.updateRides, payload: {
                  //   'id': controller.rideId,
                  //   'rideTimeStart': DateTime.now().toString(),
                  //   'status': 'Applied'
                  // });
                  // controller.driverArrivePassenger();
                  // // Send notification to driver to alert him that trip is begin
                  // FirebaseMessagesController()
                  //     .sendNotificationToAnyWithoutData(
                  //   'BeginTrip',
                  //   box.read(BoxName.name).toString(),
                  //   controller.driverToken.toString(),
                  // );
                  // print(controller.driverToken.toString());
                  // Get.defaultDialog(
                  //   title: 'The Ride is Begin'.tr,
                  //   backgroundColor: AppColor.greenColor,
                  // );
                  //     })
                  // : const SizedBox()
                ],
              ),
            ),
          ),
        );
      } else {
        return const SizedBox();
      }
    });
  }
}

class StreamCounter extends StatelessWidget {
  const StreamCounter({Key? key}) : super(key: key);

  @override
  // Build the UI based on the timer value
  Widget build(BuildContext context) {
    Get.put(MapPassengerController());
    return GetBuilder<MapPassengerController>(builder: (controller) {
      return StreamBuilder<int>(
        initialData: 0,
        stream: controller.timerController.stream,
        builder: (context, snapshot) {
          // Calculate the remaining time based on the current tick
          final remainingTime = controller.durationToRide - snapshot.data!;

          // Format the remaining time as a string
          final formattedRemainingTime =
              '${(remainingTime / 60).floor()}:${(remainingTime % 60).toString().padLeft(2, '0')}';

          // Return the UI widgets based on the remaining time
          return Column(
            children: [
              Text(formattedRemainingTime),
              // ElevatedButton(
              //   onPressed: () {
              //     // Handle button press here
              //   },
              // ),
            ],
          );
        },
      );
    });
  }
}
