import 'package:Intaleq/constant/colors.dart';
import 'package:Intaleq/constant/style.dart';
import 'package:Intaleq/controller/home/map_passenger_controller.dart';
import 'package:Intaleq/views/widgets/elevated_btn.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../constant/links.dart';
import '../../../print.dart';

class CupertinoDriverListWidget extends StatelessWidget {
  MapPassengerController mapPassengerController =
      Get.put(MapPassengerController());
  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: CupertinoNavigationBar(
        middle: Text('Driver List'.tr), // Ensure text is properly localized
      ),
      child: SafeArea(
          child: mapPassengerController.driversForMishwari.isEmpty
              ? Center(
                  child: Text(
                    'No drivers available at the moment. Please try again later.'
                        .tr,
                    style: const TextStyle(
                      fontSize: 18, // Adjust the size as needed
                      fontWeight: FontWeight.w600,
                      color: CupertinoColors.inactiveGray, // Customize color
                    ),
                    textAlign: TextAlign.center, // Center-align the text
                  ),
                )
              : ListView.separated(
                  itemCount: mapPassengerController.driversForMishwari.length,
                  separatorBuilder: (context, index) =>
                      const Divider(height: 1),
                  itemBuilder: (context, index) {
                    var driver =
                        mapPassengerController.driversForMishwari[index];
                    return Container(
                      decoration: AppStyle.boxDecoration1,
                      child: CupertinoListTile(
                        padding: const EdgeInsets.symmetric(
                            vertical: 4, horizontal: 8),
                        leading: CircleAvatar(
                          radius: 25,
                          backgroundImage: NetworkImage(
                            '${AppLink.server}/portrate_captain_image/${driver['id']}.jpg',
                          ),
                          child: Builder(
                            builder: (context) {
                              return Image.network(
                                '${AppLink.server}/portrate_captain_image/${driver['id']}.jpg',
                                fit: BoxFit.cover,
                                loadingBuilder: (BuildContext context,
                                    Widget child,
                                    ImageChunkEvent? loadingProgress) {
                                  if (loadingProgress == null) {
                                    return child; // Image is loaded
                                  } else {
                                    return Center(
                                      child: CircularProgressIndicator(
                                        value: loadingProgress
                                                    .expectedTotalBytes !=
                                                null
                                            ? loadingProgress
                                                    .cumulativeBytesLoaded /
                                                (loadingProgress
                                                        .expectedTotalBytes ??
                                                    1)
                                            : null,
                                      ),
                                    );
                                  }
                                },
                                errorBuilder: (BuildContext context,
                                    Object error, StackTrace? stackTrace) {
                                  return const Icon(
                                    Icons
                                        .person, // Icon to show when image fails to load
                                    size: 25, // Adjust the size as needed
                                    color: AppColor
                                        .blueColor, // Color for the error icon
                                  );
                                },
                              );
                            },
                          ),
                        ),
                        title: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '${driver['NAME'].toString().split(' ')[0]} ${driver['NAME'].toString().split(' ')[1]}',
                              style:
                                  const TextStyle(fontWeight: FontWeight.bold),
                            ),
                            Text('${'Age'.tr}: ${driver['age'].toString()}'),
                            Row(
                              children: [
                                const Icon(CupertinoIcons.star_fill,
                                    size: 16,
                                    color: CupertinoColors.systemYellow),
                                const SizedBox(width: 4),
                                Text(driver['rating']?.toStringAsFixed(1) ??
                                    'N/A'.tr),
                                const SizedBox(width: 8),
                                Text('${'Rides'.tr}: ${driver['ride_count']}'),
                              ],
                            ),
                          ],
                        ),
                        subtitle: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                    '${'Car'.tr}: ${driver['make']} ${driver['model']} (${driver['year']})'),
                                Text('${'Plate'.tr}: ${driver['car_plate']}'),
                              ],
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                SizedBox(
                                  // width: Get.width * .3,
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text('${'Color'.tr}: ${driver['color']}'),
                                      const SizedBox(width: 8),
                                      Container(
                                        width: 20,
                                        height: 20,
                                        decoration: BoxDecoration(
                                          color: driver['color_hex']
                                                      .toString() ==
                                                  'null'
                                              ? Colors.amber
                                              : hexToColor(driver['color_hex']
                                                  .toString()),
                                          borderRadius:
                                              BorderRadius.circular(4),
                                          border: Border.all(),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                        onTap: () {
                          Log.print(' driver["id"]: ${driver['driver_id']}');
                          Get.find<MapPassengerController>().driverIdVip =
                              driver['driver_id'];

                          // Handle driver selection
                          Get.defaultDialog(
                              title:
                                  '${'Selected driver'.tr}: ${driver['NAME']}',
                              content: Column(
                                children: [
                                  Column(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                          '${'Car'.tr}: ${driver['make']} ${driver['model']} (${driver['year']})'),
                                      Text(
                                          '${'Plate'.tr}: ${driver['car_plate']}'),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Text(
                                              '${'Color'.tr}: ${driver['color']}'),
                                          const SizedBox(width: 8),
                                          Container(
                                            width: 20,
                                            height: 20,
                                            decoration: BoxDecoration(
                                              color: driver['color_hex']
                                                          .toString() ==
                                                      'null'
                                                  ? Colors.amber
                                                  : hexToColor(
                                                      driver['color_hex']
                                                          .toString()),
                                              borderRadius:
                                                  BorderRadius.circular(4),
                                              border: Border.all(),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                              confirm: MyElevatedButton(
                                  title: 'OK'.tr,
                                  onPressed: () {
                                    Get.back();
                                    showDateTimePickerDialog(driver);
                                  }));
                          print('${'Selected driver'.tr}: ${driver['NAME']}');
                          // Get.back(); // Close the dialog
                        },
                      ),
                    );
                  },
                )),
    );
  }

  Color hexToColor(String hexColor) {
    hexColor = hexColor.replaceAll("#", "");
    String colorString = "ff$hexColor";
    return Color(int.parse(colorString, radix: 16));
  }

  void showDriverSelectionDialog(Map<String, dynamic> driver) {
    Get.defaultDialog(
      title: '${'Selected driver'.tr}: ${driver['name']}',
      content: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
              '${'Car'.tr}: ${driver['make']} ${driver['model']} (${driver['year']})'),
          Text('${'Plate'.tr}: ${driver['car_plate']}'),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('${'Color'.tr}: ${driver['color']}'),
              const SizedBox(width: 8),
              Container(
                width: 20,
                height: 20,
                decoration: BoxDecoration(
                  color: driver['color_hex'].toString() == 'null'
                      ? Colors.amber
                      : hexToColor(driver['color_hex'].toString()),
                  borderRadius: BorderRadius.circular(4),
                  border: Border.all(),
                ),
              ),
            ],
          ),
        ],
      ),
      confirm: MyElevatedButton(
        title: 'OK'.tr,
        onPressed: () {
          Get.back();
          showDateTimePickerDialog(driver);
        },
      ),
    );
  }

  void showDateTimePickerDialog(Map<String, dynamic> driver) {
    DateTime selectedDateTime = DateTime.now();

    Get.defaultDialog(
      barrierDismissible: false,
      title: "Select date and time of trip".tr,
      content: SizedBox(
        // height: 400, // Adjust height as needed
        width: double.maxFinite,
        child: Column(
          children: [
            DateTimePickerWidget(),
          ],
        ),
      ),
      confirm: MyElevatedButton(
        title: 'Confirm Trip'.tr,
        onPressed: () async {
          DateTime selectedDateTime =
              mapPassengerController.selectedDateTime.value;
          // Save trip data and set up notifications
          Get.back();
          await mapPassengerController.saveTripData(driver, selectedDateTime);
        },
      ),
      cancel: MyElevatedButton(
        kolor: AppColor.redColor,
        title: 'Cancel'.tr,
        onPressed: () {
          Get.back();
        },
      ),
    );
  }
}

class DateTimePickerWidget extends StatelessWidget {
  final MapPassengerController controller = Get.put(MapPassengerController());

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: CupertinoNavigationBar(
        transitionBetweenRoutes: false,
        automaticallyImplyLeading: false,
        middle: Text('Date and Time Picker'.tr),
      ),
      child: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Obx(() => Text(
                  '${'Selected Date and Time'.tr}: ${controller.selectedDateTime.value}',
                  style: const TextStyle(fontSize: 18),
                  textAlign: TextAlign.center,
                )),
            const SizedBox(height: 20),
            SizedBox(
              height: 200,
              child: CupertinoDatePicker(
                mode: CupertinoDatePickerMode.dateAndTime,
                initialDateTime: controller.selectedDateTime.value,
                onDateTimeChanged: (newDateTime) {
                  controller.updateDateTime(newDateTime);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
