import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/constant/colors.dart';
import 'package:Intaleq/constant/style.dart';
import 'package:Intaleq/main.dart';
import 'package:Intaleq/views/home/profile/passenger_profile_page.dart';
import 'package:Intaleq/views/widgets/elevated_btn.dart';
import 'package:Intaleq/views/widgets/my_textField.dart';
import 'dart:ui';

import '../../../constant/info.dart';
import '../../../controller/functions/tts.dart';
import '../../../controller/home/map_passenger_controller.dart';
import '../../../print.dart';
import '../../widgets/mydialoug.dart';

// --- CarType class (unchanged) ---
class CarType {
  final String carType;
  final String carDetail;
  final String image;
  bool isSelected = false;

  CarType(
      {required this.carType, required this.carDetail, required this.image});
}

// --- List of Car Types with NEW order and 'Electric' car ---
List<CarType> carTypes = [
  CarType(
      carType: 'Speed',
      carDetail: 'Closest & Cheapest'.tr,
      image: 'assets/images/carspeed.png'), // First choice
  CarType(
      carType: 'Comfort',
      carDetail: 'Comfort choice'.tr,
      image: 'assets/images/blob.png'), // Second choice
  CarType(
      carType: 'Electric',
      carDetail: 'Quiet & Eco-Friendly'.tr,
      image:
          'assets/images/electric.png'), // Third choice - NOTE: Use your actual image path
  CarType(
      carType: 'Lady',
      carDetail: 'Lady Captain for girls'.tr,
      image: 'assets/images/lady.png'),
  CarType(
      carType: 'Van',
      carDetail: 'Van for familly'.tr,
      image: 'assets/images/bus.png'),
  // CarType(
  //     carType: 'Scooter',
  //     carDetail: 'Delivery service'.tr,
  //     image: 'assets/images/moto.png'),
  CarType(
      carType: 'Rayeh Gai',
      carDetail: "Best choice for cities".tr,
      image: 'assets/images/roundtrip.png'),
];

// --- Main Widget ---
class CarDetailsTypeToChoose extends StatelessWidget {
  CarDetailsTypeToChoose({super.key});
  final textToSpeechController = Get.put(TextToSpeechController());

  void _prepareCarTypes(MapPassengerController controller) {
    if (controller.distance > 33) {
      if (!carTypes.any((car) => car.carType == 'Rayeh Gai')) {
        carTypes.add(CarType(
            carType: 'Rayeh Gai',
            carDetail: "Best choice for cities".tr,
            image: 'assets/images/roundtrip.png'));
      }
    } else {
      carTypes.removeWhere((car) => car.carType == 'Rayeh Gai');
    }
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MapPassengerController>(builder: (controller) {
      _prepareCarTypes(controller);

      if (!(controller.data.isNotEmpty &&
          controller.isBottomSheetShown &&
          controller.rideConfirm == false)) {
        return const SizedBox.shrink();
      }

      return Positioned(
        bottom: 0,
        left: 0,
        right: 0,
        child: Container(
          decoration: BoxDecoration(
            color: AppColor.secondaryColor,
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(24),
              topRight: Radius.circular(24),
            ),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.2),
                blurRadius: 20,
                spreadRadius: 5,
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildHeader(controller),
              const Divider(height: 1),
              _buildNegativeBalanceWarning(controller),
              SizedBox(
                height: 130,
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  padding:
                      const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  itemCount: carTypes.length,
                  itemBuilder: (context, index) {
                    final carType = carTypes[index];
                    final isSelected = controller.selectedIndex == index;
                    return _buildHorizontalCarCard(
                        context, controller, carType, isSelected, index);
                  },
                ),
              ),
              _buildPromoButton(context, controller),
            ],
          ),
        ),
      );
    });
  }

  // --- All other methods are here, with updates for 'Electric' car ---

  Widget _buildPromoButton(
      BuildContext context, MapPassengerController controller) {
    if (controller.promoTaken) {
      return const SizedBox.shrink();
    }

    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
      child: OutlinedButton(
        onPressed: () => _showPromoCodeDialog(context, controller),
        style: OutlinedButton.styleFrom(
          padding: const EdgeInsets.symmetric(vertical: 14),
          backgroundColor: AppColor.primaryColor.withOpacity(0.05),
          side: BorderSide(
            color: AppColor.primaryColor.withOpacity(0.7),
            width: 1.5,
          ),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.local_offer_outlined,
                color: AppColor.primaryColor, size: 20),
            const SizedBox(width: 8),
            Text(
              'Have a promo code?'.tr,
              style: AppStyle.title
                  .copyWith(fontSize: 16, color: AppColor.primaryColor),
            ),
          ],
        ),
      ),
    );
  }

  void _showPromoCodeDialog(
      BuildContext context, MapPassengerController controller) {
    Get.dialog(
      Dialog(
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
        backgroundColor: AppColor.secondaryColor,
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Form(
            key: controller.promoFormKey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Text(
                  'Apply Promo Code'.tr,
                  textAlign: TextAlign.center,
                  style: AppStyle.headTitle.copyWith(fontSize: 22),
                ),
                const SizedBox(height: 8),
                Text(
                  'Enter your code below to apply the discount.'.tr,
                  textAlign: TextAlign.center,
                  style: AppStyle.subtitle
                      .copyWith(color: AppColor.writeColor.withOpacity(0.7)),
                ),
                const SizedBox(height: 24),
                MyTextForm(
                  controller: controller.promo,
                  label: 'Promo Code'.tr,
                  hint: 'Enter your promo code'.tr,
                  type: TextInputType.text,
                ),
                const SizedBox(height: 24),
                Row(
                  children: [
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () => Get.back(),
                        style: OutlinedButton.styleFrom(
                          foregroundColor: AppColor.writeColor,
                          padding: const EdgeInsets.symmetric(vertical: 14),
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12)),
                          side: BorderSide(
                              color: AppColor.writeColor.withOpacity(0.3)),
                        ),
                        child: Text('Cancel'.tr),
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: MyElevatedButton(
                        title: 'Apply'.tr,
                        onPressed: () {
                          if (controller.promoFormKey.currentState!
                              .validate()) {
                            controller.applyPromoCodeToPassenger(context);
                            Get.back();
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
      barrierColor: Colors.black.withOpacity(0.5),
    );
  }

  Widget _buildHorizontalCarCard(
      BuildContext context,
      MapPassengerController controller,
      CarType carType,
      bool isSelected,
      int index) {
    return InkWell(
      onTap: () {
        controller.selectCarFromList(index);
        _showCarDetailsDialog(
            context, controller, carType, textToSpeechController);
      },
      borderRadius: BorderRadius.circular(16),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        width: 110,
        margin: const EdgeInsets.only(right: 12),
        decoration: BoxDecoration(
          color: isSelected
              ? AppColor.primaryColor.withOpacity(0.15)
              : AppColor.writeColor.withOpacity(0.05),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color: isSelected ? AppColor.primaryColor : Colors.transparent,
            width: 2.0,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(carType.image, height: 50),
            const SizedBox(height: 8),
            Text(
              carType.carType.tr,
              style: AppStyle.subtitle
                  .copyWith(fontWeight: FontWeight.bold, fontSize: 14),
              textAlign: TextAlign.center,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            const SizedBox(height: 4),
            _buildPriceDisplay(controller, carType),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader(MapPassengerController controller) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Choose your ride'.tr,
                  style: AppStyle.headTitle.copyWith(fontSize: 22)),
              const SizedBox(height: 4),
              Text(
                '${controller.distance} ${'KM'.tr} • ${controller.hours > 0 ? '${controller.hours}h ${controller.minutes}m' : '${controller.minutes} min'}',
                style: AppStyle.subtitle.copyWith(
                    color: AppColor.primaryColor, fontWeight: FontWeight.bold),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildNegativeBalanceWarning(MapPassengerController controller) {
    final passengerWallet =
        double.tryParse(box.read(BoxName.passengerWalletTotal) ?? '0.0') ?? 0.0;
    if (passengerWallet < 0.0) {
      return Container(
        color: AppColor.redColor.withOpacity(0.8),
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Row(
          children: [
            const Icon(Icons.error_outline, color: Colors.white, size: 24),
            const SizedBox(width: 12),
            Expanded(
                child: Text(
                    '${'You have a negative balance of'.tr} ${passengerWallet.toStringAsFixed(2)} ${'SYP'.tr}.',
                    style: AppStyle.subtitle.copyWith(color: Colors.white))),
          ],
        ),
      );
    }
    return const SizedBox.shrink();
  }

  Widget _buildPriceDisplay(
      MapPassengerController mapPassengerController, CarType carType) {
    return Text(
        '${_getPassengerPriceText(carType, mapPassengerController)} ${'SYP'.tr}',
        style: AppStyle.subtitle.copyWith(
            fontSize: 14,
            fontWeight: FontWeight.bold,
            color: AppColor.primaryColor));
  }

  // UPDATED to include 'Electric'
  String _getPassengerPriceText(
      CarType carType, MapPassengerController mapPassengerController) {
    switch (carType.carType) {
      case 'Comfort':
        return mapPassengerController.totalPassengerComfort.toStringAsFixed(1);
      case 'Speed':
        return mapPassengerController.totalPassengerSpeed.toStringAsFixed(1);
      case 'Electric':
        return mapPassengerController.totalPassengerElectric.toStringAsFixed(1);
      case 'Awfar Car':
        return mapPassengerController.totalPassengerBalash.toStringAsFixed(1);
      case 'Scooter':
        return mapPassengerController.totalPassengerScooter.toStringAsFixed(1);
      case 'Van':
        return mapPassengerController.totalPassengerVan.toStringAsFixed(1);
      case 'Lady':
        return mapPassengerController.totalPassengerLady.toStringAsFixed(1);
      case 'Pink Bike':
        return mapPassengerController.totalPassengerScooter.toStringAsFixed(1);
      case 'Rayeh Gai':
        return mapPassengerController.totalPassengerRayehGai.toStringAsFixed(1);
      default:
        return '...';
    }
  }

  void _showCarDetailsDialog(
      BuildContext context,
      MapPassengerController mapPassengerController,
      CarType carType,
      TextToSpeechController textToSpeechController) {
    Get.dialog(
      Dialog(
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(24.0)),
        backgroundColor: AppColor.secondaryColor,
        child: Padding(
          padding: const EdgeInsets.fromLTRB(20, 24, 20, 20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(carType.image, height: 70),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    carType.carType.tr,
                    style: AppStyle.headTitle.copyWith(fontSize: 22),
                  ),
                  const SizedBox(width: 8),
                  IconButton(
                    onPressed: () => textToSpeechController.speakText(
                        _getCarDescription(mapPassengerController, carType)),
                    icon: Icon(Icons.volume_up_outlined,
                        color: AppColor.primaryColor, size: 24),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                _getCarDescription(mapPassengerController, carType),
                textAlign: TextAlign.center,
                style: AppStyle.subtitle.copyWith(
                  color: AppColor.writeColor.withOpacity(0.7),
                  fontSize: 15,
                  height: 1.4,
                ),
              ),
              const SizedBox(height: 24),
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () => Get.back(),
                      style: TextButton.styleFrom(
                        foregroundColor: AppColor.writeColor.withOpacity(0.8),
                        padding: const EdgeInsets.symmetric(vertical: 14),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12)),
                      ),
                      child: Text('Cancel'.tr),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: MyElevatedButton(
                      kolor: AppColor.greenColor,
                      title: 'Next'.tr,
                      onPressed: () {
                        Get.back();
                        _handleCarSelection(
                            context, mapPassengerController, carType);
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
      barrierColor: Colors.black.withOpacity(0.5),
    );
  }

  // UPDATED to include 'Electric'
  String _getCarDescription(
      MapPassengerController mapPassengerController, CarType carType) {
    switch (carType.carType) {
      case 'Comfort':
        return mapPassengerController.endNameAddress
                .toLowerCase()
                .contains("airport".tr)
            ? "Best choice for a comfortable car with a flexible route and stop points. This airport offers visa entry at this price."
                .tr
            : 'Best choice for comfort car and flexible route and stops point'
                .tr;
      case 'Speed':
        return 'This trip goes directly from your starting point to your destination for a fixed price. The driver must follow the planned route'
            .tr;
      case 'Electric':
        return 'Travel in a modern, silent electric car. A premium, eco-friendly choice for a smooth ride.'
            .tr;
      case 'Scooter':
      case 'Van':
        return "Spacious van service ideal for families and groups. Comfortable, safe, and cost-effective travel together."
            .tr;
      case 'Pink Bike':
        return 'This is for delivery or a motorcycle.'.tr;
      case 'Mishwar Vip':
        return "Perfect for passengers seeking the latest car models with the freedom to choose any route they desire"
            .tr;
      case 'Awfar Car':
        return "Old and affordable, perfect for budget rides.".tr;
      case 'Lady':
        return "This trip is for women only".tr;
      case 'Rayeh Gai':
        return "Rayeh Gai: Round trip service for convenient travel between cities, easy and reliable."
            .tr;
      default:
        return '';
    }
  }

  void _handleCarSelection(BuildContext context,
      MapPassengerController mapPassengerController, CarType carType) {
    box.write(BoxName.carType, carType.carType);
    mapPassengerController.totalPassenger =
        _getOriginalPrice(carType, mapPassengerController);
    if (carType.carType == 'Mishwar Vip') {
      Get.back();
      mapPassengerController.mishwariOption();
    } else if (carType.carType == 'Lady') {
      if (box.read(BoxName.gender).toString() != '') {
        mapPassengerController.isBottomSheetShown = false;
        mapPassengerController.update();
        mapPassengerController.changeCashConfirmPageShown();
      } else {
        MyDialog().getDialog('Idintify gender',
            'You should ideintify your gender for this type of trip!'.tr, () {
          Get.to(() => PassengerProfilePage());
        });
      }
    } else if (carType.carType == 'Rayeh Gai') {
      Get.defaultDialog(
          barrierDismissible: false,
          title: "Select betweeen types".tr,
          content:
              Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            _buildRayehGaiOption(mapPassengerController, 'Awfar Car',
                mapPassengerController.totalPassengerRayehGaiBalash),
            _buildRayehGaiOption(mapPassengerController, 'Speed',
                mapPassengerController.totalPassengerRayehGai),
            _buildRayehGaiOption(mapPassengerController, 'Comfort',
                mapPassengerController.totalPassengerRayehGaiComfort)
          ]),
          cancel: MyElevatedButton(
              kolor: AppColor.redColor,
              title: 'Cancel'.tr,
              onPressed: () => Get.back()),
          confirm: MyElevatedButton(
              kolor: AppColor.greenColor,
              title: 'Next'.tr,
              onPressed: () {
                mapPassengerController.isBottomSheetShown = false;
                mapPassengerController.update();
                mapPassengerController.changeCashConfirmPageShown();
              }));
    } else {
      mapPassengerController.isBottomSheetShown = false;
      mapPassengerController.update();
      mapPassengerController.changeCashConfirmPageShown();
    }
  }

  // UPDATED to include 'Electric'
  double _getOriginalPrice(
      CarType carType, MapPassengerController mapPassengerController) {
    switch (carType.carType) {
      case 'Comfort':
        return mapPassengerController.totalPassengerComfort;
      case 'Speed':
        return mapPassengerController.totalPassengerSpeed;
      case 'Electric':
        return mapPassengerController.totalPassengerElectric;
      case 'Awfar Car':
        return mapPassengerController.totalPassengerBalash;
      case 'Van':
        return mapPassengerController.totalPassengerVan;
      case 'Lady':
        return mapPassengerController.totalPassengerLady;
      default:
        return 0.0;
    }
  }

  Widget _buildRayehGaiOption(MapPassengerController mapPassengerController,
      String carTypeName, double price) {
    return GestureDetector(
      onTap: () {
        Get.back();
        mapPassengerController.totalPassenger = price;
        mapPassengerController.isBottomSheetShown = false;
        mapPassengerController.update();
        mapPassengerController.changeCashConfirmPageShown();
      },
      child: Container(
          decoration: AppStyle.boxDecoration1,
          padding: const EdgeInsets.all(8.0),
          child: Column(children: [
            Text(carTypeName.tr),
            Text(price.toStringAsFixed(0))
          ])),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MapPassengerController>(
      builder: (mapPassengerController) {
        final passengerWallet =
            double.tryParse(box.read(BoxName.passengerWalletTotal) ?? '0.0') ??
                0.0;

        return mapPassengerController.data.isNotEmpty &&
                mapPassengerController.isBottomSheetShown &&
                !mapPassengerController.rideConfirm &&
                passengerWallet < 0.0
            ? Positioned(
                bottom: Get.height * .41,
                left: 16,
                right: 16,
                child: Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: AppColor.redColor.withOpacity(0.8),
                    borderRadius: BorderRadius.circular(8),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.1),
                        blurRadius: 4,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Row(
                    children: [
                      const Icon(
                        Icons.warning_amber_rounded,
                        color: Colors.white,
                        size: 24,
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text.rich(
                          TextSpan(
                            children: [
                              TextSpan(
                                text: '${'Negative Balance:'.tr} ',
                                style: AppStyle.subtitle.copyWith(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              TextSpan(
                                text:
                                    '${'You have a balance of'.tr} ${passengerWallet.toStringAsFixed(2)} ${box.read(BoxName.countryCode) == 'Egypt' ? 'LE'.tr : 'SYP'.tr} ${'due to a previous trip.'.tr}',
                                style: AppStyle.subtitle.copyWith(
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                          textAlign: TextAlign.start,
                        ),
                      ),
                      const SizedBox(width: 8),
                      GestureDetector(
                        onTap: () async =>
                            await Get.find<TextToSpeechController>().speakText(
                                '${'you have a negative balance of'.tr}${passengerWallet.toStringAsFixed(2)}${' in your'.tr} ${AppInformation.appName}${' wallet due to a previous trip.'.tr}'),
                        child: const Icon(
                          Icons.headphones,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
              )
            : const SizedBox();
      },
    );
  }
}
