import 'package:siro_rider/constant/currency.dart';
import 'package:flutter/material.dart';
import 'package:siro_rider/controller/home/map/map_engine_controller.dart';
import 'package:get/get.dart';
import 'package:siro_rider/constant/box_name.dart';
import 'package:siro_rider/constant/colors.dart';
import 'package:siro_rider/constant/style.dart';
import 'package:siro_rider/main.dart';
import 'package:siro_rider/views/home/profile/passenger_profile_page.dart';
import 'package:siro_rider/views/widgets/elevated_btn.dart';
import 'package:siro_rider/views/widgets/my_textField.dart';
import 'package:intl/intl.dart';
import 'dart:ui';

import '../../../constant/info.dart';
import '../../../controller/functions/tts.dart';
import '../../../controller/home/map/ride_lifecycle_controller.dart';
import '../../widgets/mydialoug.dart';

// ─────────────────────────────────────────────────────────────────────────────
//  CAR TYPE MODEL
// ─────────────────────────────────────────────────────────────────────────────
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<CarType> carTypes = [
  CarType(
      carType: 'Fixed Price',
      carDetail: 'Closest & Cheapest'.tr,
      image: 'assets/images/carspeed.png'),
  CarType(
      carType: 'Comfort',
      carDetail: 'Comfort choice'.tr,
      image: 'assets/images/blob.png'),
  CarType(
      carType: 'Electric',
      carDetail: 'Quiet & Eco-Friendly'.tr,
      image: 'assets/images/electric.png'),
  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: '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.find<TextToSpeechController>();

  void _prepareCarTypes(RideLifecycleController controller) {
    if (controller.distance > 23) {
      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<RideLifecycleController>(builder: (controller) {
      _prepareCarTypes(controller);

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

      return Positioned(
        bottom: 0,
        left: 0,
        right: 0,
        child: ClipRRect(
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(28),
            topRight: Radius.circular(28),
          ),
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 12, sigmaY: 12),
            child: Container(
              decoration: BoxDecoration(
                color: AppColor.secondaryColor.withAlpha(240),
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(28),
                  topRight: Radius.circular(28),
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withAlpha(30),
                    blurRadius: 30,
                    spreadRadius: 0,
                    offset: const Offset(0, -8),
                  ),
                ],
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // ── Drag Handle ──────────────────────────────────────
                  Center(
                    child: Container(
                      width: 40,
                      height: 4,
                      margin: const EdgeInsets.only(top: 12, bottom: 8),
                      decoration: BoxDecoration(
                        color: Colors.grey.shade300,
                        borderRadius: BorderRadius.circular(2),
                      ),
                    ),
                  ),

                  // ── Header ───────────────────────────────────────────
                  _buildHeader(controller),

                  // ── Negative Balance Warning ─────────────────────────
                  _buildNegativeBalanceWarning(controller),

                  // ── Car Selection List ───────────────────────────────
                  SizedBox(
                    height: 170,
                    child: ListView.builder(
                      physics: const BouncingScrollPhysics(),
                      scrollDirection: Axis.horizontal,
                      padding: const EdgeInsets.fromLTRB(20, 8, 20, 12),
                      itemCount: carTypes.length,
                      itemBuilder: (context, index) {
                        final carType = carTypes[index];
                        final isSelected = controller.selectedIndex == index;
                        return Padding(
                          padding: EdgeInsets.only(
                              right: index < carTypes.length - 1 ? 10 : 0),
                          child: _buildCarCard(
                              context, controller, carType, isSelected, index),
                        );
                      },
                    ),
                  ),

                  // ── Promo Code & Actions ─────────────────────────────
                  _buildPromoButton(context, controller),

                  SizedBox(height: MediaQuery.of(context).padding.bottom + 10),
                ],
              ),
            ),
          ),
        ),
      );
    });
  }

  // ═══════════════════════════════════════════════════════════════════════════
  //  HEADER
  // ═══════════════════════════════════════════════════════════════════════════
  Widget _buildHeader(RideLifecycleController controller) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(22, 4, 22, 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              // Title
              Expanded(
                child: Text(
                  'Choose your ride'.tr,
                  style: AppStyle.headTitle.copyWith(
                    fontSize: 20,
                    fontWeight: FontWeight.w800,
                    letterSpacing: 0.3,
                  ),
                ),
              ),
              // Close button
              GestureDetector(
                onTap: () {
                  controller.isBottomSheetShown = false;
                  controller.update();
                },
                child: Container(
                  padding: const EdgeInsets.all(6),
                  decoration: BoxDecoration(
                    color: Get.isDarkMode
                        ? Colors.white.withOpacity(0.08)
                        : Colors.grey.shade100,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(Icons.close_rounded,
                      size: 18, color: AppColor.grayColor),
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),
          // Trip Stats Row
          Row(
            children: [
              // Distance chip
              _buildStatChip(
                icon: Icons.route_rounded,
                value: '${controller.distance.toStringAsFixed(1)} ${'KM'.tr}',
                color: AppColor.primaryColor,
              ),
              const SizedBox(width: 8),
              // Duration chip
              _buildStatChip(
                icon: Icons.schedule_rounded,
                value: controller.hours > 0
                    ? '${controller.hours}h ${controller.minutes}m'
                    : '${controller.minutes} ${'min'.tr}',
                color: const Color(0xFF6366F1), // Indigo
              ),
              const Spacer(),
              // Price preview for selected car
              if (controller.selectedIndex >= 0 &&
                  controller.selectedIndex < carTypes.length)
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        AppColor.primaryColor,
                        AppColor.primaryColor.withAlpha(200),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Text(
                    '${_getPassengerPriceText(carTypes[controller.selectedIndex], controller)} ${CurrencyHelper.currency}',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 13,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatChip(
      {required IconData icon, required String value, required Color color}) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      decoration: BoxDecoration(
        color: color.withAlpha(20),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: color.withAlpha(50)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: color),
          const SizedBox(width: 5),
          Text(
            value,
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w700,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  // ═══════════════════════════════════════════════════════════════════════════
  //  CAR CARD
  // ═══════════════════════════════════════════════════════════════════════════
  Widget _buildCarCard(BuildContext context, RideLifecycleController controller,
      CarType carType, bool isSelected, int index) {
    return GestureDetector(
      onTap: () {
        controller.selectCarFromList(index);
        _showCarDetailsDialog(
            context, controller, carType, textToSpeechController);
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOutCubic,
        width: 108,
        decoration: BoxDecoration(
          gradient: isSelected
              ? LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    AppColor.primaryColor.withAlpha(18),
                    AppColor.primaryColor.withAlpha(8),
                  ],
                )
              : null,
          color: isSelected ? null : AppColor.secondaryColor,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color: isSelected
                ? AppColor.primaryColor
                : AppColor.grayColor.withOpacity(0.2),
            width: isSelected ? 2.0 : 1.0,
          ),
          boxShadow: [
            BoxShadow(
              color: isSelected
                  ? AppColor.primaryColor.withAlpha(40)
                  : Colors.black.withAlpha(12),
              blurRadius: isSelected ? 12 : 4,
              offset: const Offset(0, 3),
            ),
          ],
        ),
        child: Stack(
          children: [
            // Selected indicator
            if (isSelected)
              Positioned(
                top: 6,
                right: 6,
                child: Container(
                  width: 18,
                  height: 18,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        AppColor.primaryColor,
                        AppColor.primaryColor.withAlpha(200),
                      ],
                    ),
                    shape: BoxShape.circle,
                    boxShadow: [
                      BoxShadow(
                        color: AppColor.primaryColor.withAlpha(60),
                        blurRadius: 6,
                      ),
                    ],
                  ),
                  child: const Icon(Icons.check, size: 11, color: Colors.white),
                ),
              ),

            // Card content
            Padding(
              padding: const EdgeInsets.fromLTRB(8, 10, 8, 8),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // Car image
                  AnimatedScale(
                    scale: isSelected ? 1.12 : 1.0,
                    duration: const Duration(milliseconds: 300),
                    child: Image.asset(
                      carType.image,
                      height: 48,
                      fit: BoxFit.contain,
                    ),
                  ),
                  const SizedBox(height: 10),

                  // Car name
                  FittedBox(
                    fit: BoxFit.scaleDown,
                    child: Text(
                      carType.carType.tr,
                      style: TextStyle(
                        fontWeight:
                            isSelected ? FontWeight.w800 : FontWeight.w600,
                        fontSize: 13,
                        color: isSelected
                            ? AppColor.primaryColor
                            : AppColor.writeColor,
                      ),
                      maxLines: 1,
                    ),
                  ),

                  const SizedBox(height: 6),

                  // Price tag
                  Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: isSelected
                          ? AppColor.primaryColor
                          : AppColor.writeColor.withOpacity(0.05),
                      borderRadius: BorderRadius.circular(10),
                      border: isSelected
                          ? null
                          : Border.all(
                              color: AppColor.grayColor.withOpacity(0.2)),
                    ),
                    child: FittedBox(
                      child: Text(
                        '${_getPassengerPriceText(carType, controller)} ${CurrencyHelper.currency}',
                        style: TextStyle(
                          fontSize: 11,
                          fontWeight: FontWeight.w700,
                          color: isSelected
                              ? Colors.white
                              : AppColor.writeColor.withOpacity(0.8),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // ═══════════════════════════════════════════════════════════════════════════
  //  PROMO BUTTON
  // ═══════════════════════════════════════════════════════════════════════════
  Widget _buildPromoButton(
      BuildContext context, RideLifecycleController controller) {
    if (controller.promoTaken) return const SizedBox.shrink();

    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 6, 20, 4),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => _showPromoCodeDialog(context, controller),
          borderRadius: BorderRadius.circular(14),
          child: Container(
            padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 14),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Colors.amber.shade50,
                  Colors.orange.shade50,
                ],
              ),
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: Colors.amber.shade200),
            ),
            child: Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(7),
                  decoration: BoxDecoration(
                    color: Colors.amber.shade100,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(Icons.percent_rounded,
                      color: Colors.amber.shade800, size: 16),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Have a Promo Code?'.tr,
                        style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w700,
                          color: Colors.amber.shade900,
                        ),
                      ),
                      Text(
                        'Tap to apply your discount'.tr,
                        style: TextStyle(
                            fontSize: 11, color: Colors.amber.shade700),
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: const EdgeInsets.all(4),
                  decoration: BoxDecoration(
                    color: Colors.amber.shade100,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(Icons.arrow_forward_ios_rounded,
                      size: 12, color: Colors.amber.shade800),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // ═══════════════════════════════════════════════════════════════════════════
  //  NEGATIVE BALANCE WARNING
  // ═══════════════════════════════════════════════════════════════════════════
  Widget _buildNegativeBalanceWarning(RideLifecycleController controller) {
    final passengerWallet =
        double.tryParse(box.read(BoxName.passengerWalletTotal) ?? '0.0') ?? 0.0;
    if (passengerWallet < 0.0) {
      return Container(
        margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 6),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.red.shade50,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.red.shade200),
        ),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(6),
              decoration: BoxDecoration(
                color: Colors.red.shade100,
                shape: BoxShape.circle,
              ),
              child: Icon(Icons.warning_amber_rounded,
                  color: Colors.red.shade700, size: 18),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: Text(
                '${'You have a negative balance of'.tr} ${passengerWallet.toStringAsFixed(2)} ${CurrencyHelper.currency}.',
                style: TextStyle(
                  color: Colors.red.shade800,
                  fontWeight: FontWeight.w600,
                  fontSize: 12,
                ),
              ),
            ),
          ],
        ),
      );
    }
    return const SizedBox.shrink();
  }

  // ═══════════════════════════════════════════════════════════════════════════
  //  PRICING HELPERS (Unchanged logic)
  // ═══════════════════════════════════════════════════════════════════════════
  String _getPassengerPriceText(
      CarType carType, RideLifecycleController mapPassengerController) {
    String rawPrice;
    switch (carType.carType) {
      case 'Comfort':
        rawPrice = mapPassengerController.totalPassengerComfort;
        break;
      case 'Fixed Price':
        rawPrice = mapPassengerController.totalPassengerSpeed;
        break;
      case 'Electric':
        rawPrice = mapPassengerController.totalPassengerElectric;
        break;
      case 'Awfar Car':
        rawPrice = mapPassengerController.totalPassengerBalash;
        break;
      case 'Scooter':
      case 'Pink Bike':
        rawPrice = mapPassengerController.totalPassengerScooter;
        break;
      case 'Van':
        rawPrice = mapPassengerController.totalPassengerVan;
        break;
      case 'Lady':
        rawPrice = mapPassengerController.totalPassengerLady;
        break;
      case 'Rayeh Gai':
        rawPrice = mapPassengerController.totalPassengerRayehGai;
        break;
      default:
        return '...';
    }
    return rawPrice;
  }

  // ═══════════════════════════════════════════════════════════════════════════
  //  DIALOGS
  // ═══════════════════════════════════════════════════════════════════════════
  void _showPromoCodeDialog(
      BuildContext context, RideLifecycleController controller) {
    Get.dialog(
      Dialog(
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
        backgroundColor: AppColor.secondaryColor,
        elevation: 10,
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Form(
            key: controller.promoFormKey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Icon(Icons.local_activity_outlined,
                    size: 40, color: AppColor.primaryColor),
                const SizedBox(height: 16),
                Text(
                  'Apply Promo Code'.tr,
                  textAlign: TextAlign.center,
                  style: AppStyle.headTitle.copyWith(fontSize: 20),
                ),
                const SizedBox(height: 8),
                Text(
                  'Enter your code below to apply the discount.'.tr,
                  textAlign: TextAlign.center,
                  style: AppStyle.subtitle
                      .copyWith(color: Colors.grey.shade600, fontSize: 14),
                ),
                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: TextButton(
                        onPressed: () => Navigator.of(context).pop(),
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.grey,
                        ),
                        child: Text('Cancel'.tr),
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: MyElevatedButton(
                        title: 'Apply'.tr,
                        onPressed: () {
                          if (controller.promoFormKey.currentState!
                              .validate()) {
                            controller.applyPromoCodeToPassenger(context);
                            Navigator.of(context).pop();
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
      barrierColor: Colors.black.withAlpha(130),
    );
  }

  void _showCarDetailsDialog(
      BuildContext context,
      RideLifecycleController mapPassengerController,
      CarType carType,
      TextToSpeechController textToSpeechController) {
    Get.dialog(
      Dialog(
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(28.0)),
        backgroundColor: Colors.transparent,
        child: Stack(
          clipBehavior: Clip.none,
          alignment: Alignment.topCenter,
          children: [
            Container(
              margin: const EdgeInsets.only(top: 55),
              padding: const EdgeInsets.fromLTRB(24, 65, 24, 20),
              decoration: BoxDecoration(
                color: AppColor.secondaryColor,
                borderRadius: BorderRadius.circular(28.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withAlpha(30),
                    blurRadius: 30,
                    offset: const Offset(0, 10),
                  ),
                ],
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        carType.carType.tr,
                        style: AppStyle.headTitle.copyWith(
                          fontSize: 22,
                          fontWeight: FontWeight.w800,
                        ),
                      ),
                      const SizedBox(width: 8),
                      InkWell(
                        onTap: () => textToSpeechController.speakText(
                            _getCarDescription(
                                mapPassengerController, carType)),
                        borderRadius: BorderRadius.circular(20),
                        child: Container(
                          padding: const EdgeInsets.all(6),
                          decoration: BoxDecoration(
                            color: AppColor.primaryColor.withAlpha(20),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(Icons.volume_up_rounded,
                              color: AppColor.primaryColor, size: 20),
                        ),
                      )
                    ],
                  ),
                  const SizedBox(height: 6),
                  // Price badge in dialog
                  Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          AppColor.primaryColor,
                          AppColor.primaryColor.withAlpha(200),
                        ],
                      ),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Text(
                      '${_getPassengerPriceText(carType, mapPassengerController)} ${CurrencyHelper.currency}',
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w800,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  const SizedBox(height: 14),
                  Container(
                    padding: const EdgeInsets.all(14),
                    decoration: BoxDecoration(
                      color: Get.isDarkMode
                          ? Colors.white.withOpacity(0.05)
                          : Colors.grey.shade50,
                      borderRadius: BorderRadius.circular(14),
                      border: Border.all(
                          color: Get.isDarkMode
                              ? Colors.white10
                              : Colors.grey.shade100),
                    ),
                    child: Text(
                      _getCarDescription(mapPassengerController, carType),
                      textAlign: TextAlign.center,
                      style: AppStyle.subtitle.copyWith(
                        color: AppColor.writeColor.withOpacity(0.8),
                        fontSize: 14,
                        height: 1.5,
                      ),
                    ),
                  ),
                  const SizedBox(height: 20),
                  Row(
                    children: [
                      Expanded(
                        child: TextButton(
                          onPressed: () => Navigator.of(context).pop(),
                          style: TextButton.styleFrom(
                            padding: const EdgeInsets.symmetric(vertical: 12),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(14),
                              side: BorderSide(
                                  color: AppColor.grayColor.withOpacity(0.2)),
                            ),
                          ),
                          child: Text('Back'.tr,
                              style: TextStyle(color: AppColor.grayColor)),
                        ),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        flex: 2,
                        child: MyElevatedButton(
                          kolor: AppColor.greenColor,
                          title: 'Select This Ride'.tr,
                          onPressed: () {
                            Navigator.of(context).pop();
                            _handleCarSelection(
                                context, mapPassengerController, carType);
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            // Floating car image
            Positioned(
              top: 0,
              child: Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: AppColor.secondaryColor,
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withAlpha(30),
                      blurRadius: 15,
                      offset: const Offset(0, 5),
                    ),
                  ],
                ),
                child: Hero(
                  tag: 'car_${carType.carType}',
                  child: Image.asset(carType.image, height: 80),
                ),
              ),
            ),
          ],
        ),
      ),
      barrierColor: Colors.black.withAlpha(150),
    );
  }

  // ═══════════════════════════════════════════════════════════════════════════
  //  LOGIC HELPERS (Unchanged)
  // ═══════════════════════════════════════════════════════════════════════════
  String _getCarDescription(
      RideLifecycleController 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 'Fixed Price':
        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,
      RideLifecycleController mapPassengerController, CarType carType) {
    box.write(BoxName.carType, carType.carType);
    mapPassengerController.totalPassenger =
        _getOriginalPrice(carType, mapPassengerController);
    if (carType.carType == 'Mishwar Vip') {
      Navigator.of(context).pop();
      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(context, mapPassengerController, 'Awfar Car',
                mapPassengerController.totalPassengerRayehGaiBalash),
            _buildRayehGaiOption(context, mapPassengerController, 'Fixed Price',
                mapPassengerController.totalPassengerRayehGai),
            _buildRayehGaiOption(context, mapPassengerController, 'Comfort',
                mapPassengerController.totalPassengerRayehGaiComfort)
          ]),
          cancel: MyElevatedButton(
              kolor: AppColor.redColor,
              title: 'Cancel'.tr,
              onPressed: () => Navigator.of(context).pop()),
          confirm: MyElevatedButton(
              kolor: AppColor.greenColor,
              title: 'Next'.tr,
              onPressed: () {
                mapPassengerController.isBottomSheetShown = false;
                mapPassengerController.update();
                mapPassengerController.changeCashConfirmPageShown();
              }));
    } else {
      mapPassengerController.isBottomSheetShown = false;
      mapPassengerController.update();
      mapPassengerController.changeCashConfirmPageShown();
    }
  }

  String _getOriginalPrice(
      CarType carType, RideLifecycleController mapPassengerController) {
    switch (carType.carType) {
      case 'Comfort':
        return mapPassengerController.totalPassengerComfort;
      case 'Fixed Price':
        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';
    }
  }

  Widget _buildRayehGaiOption(BuildContext context, RideLifecycleController mapPassengerController, String carTypeName, String price) {
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pop();
        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(double.parse(price).toStringAsFixed(0))
          ])),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
//  BURC MONEY WIDGET (Floating negative balance banner)
// ─────────────────────────────────────────────────────────────────────────────
class BurcMoney extends StatelessWidget {
  const BurcMoney({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<RideLifecycleController>(
      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.withAlpha(220),
                    borderRadius: BorderRadius.circular(14),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.red.withAlpha(40),
                        blurRadius: 12,
                        offset: const Offset(0, 4),
                      ),
                    ],
                  ),
                  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 : CurrencyHelper.currency} ${'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();
      },
    );
  }
}
