import 'dart:convert'; // Though not directly used in this version's UI logic, often kept for model interactions.

import 'package:sefer_driver/controller/home/captin/home_captain_controller.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'; // For `box`
import 'package:sefer_driver/views/home/Captin/driver_map_page.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import '../../../../constant/colors.dart'; // Your AppColor
import '../../../../constant/links.dart'; // Your AppLink
import '../../../../constant/style.dart'; // Your AppStyle
import '../../../../controller/functions/crud.dart';
import '../../../../controller/functions/launch.dart';
import '../../../../controller/home/captin/order_request_controller.dart';
import '../../../widgets/elevated_btn.dart'; // Your MyElevatedButton

class OrderSpeedRequest extends StatelessWidget {
  OrderSpeedRequest({super.key});

  final OrderRequestController orderRequestController =
      Get.put(OrderRequestController());

  // Helper to make myList access more readable and safer
  String _getData(int index, {String defaultValue = ''}) {
    if (orderRequestController.myList.length > index &&
        orderRequestController.myList[index] != null) {
      return orderRequestController.myList[index].toString();
    }
    return defaultValue;
  }

  @override
  Widget build(BuildContext context) {
    // Define AppBar first to get its height for body calculations
    final appBar = AppBar(
      title: Text('Speed Order'.tr),
      leading: IconButton(
        icon: const Icon(Icons.arrow_back),
        onPressed: () => Get.back(),
      ),
      backgroundColor: AppColor.primaryColor, // Example color, adjust as needed
      elevation: 2.0,
    );

    final double appBarHeight = appBar.preferredSize.height;
    final MediaQueryData mediaQueryData = MediaQuery.of(context);
    final double screenHeight = mediaQueryData.size.height;
    final double statusBarHeight = mediaQueryData.padding.top;
    final double bottomSystemPadding = mediaQueryData.padding.bottom;

    // Calculate available height for the Scaffold's body content
    // Subtracting status bar, app bar, and bottom system padding (like navigation bar)
    final double availableBodyHeight =
        screenHeight - appBarHeight - statusBarHeight - bottomSystemPadding;

    // Define overall padding for the body content
    const EdgeInsets bodyContentPadding =
        EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0);

    // Calculate the height for the main content Column, considering the body's own padding
    double mainColumnHeight = availableBodyHeight - bodyContentPadding.vertical;
    if (mainColumnHeight < 0) mainColumnHeight = 0;

    return GetBuilder<OrderRequestController>(
      builder: (controller) {
        // Pre-extract data for readability and safety
        final String price =
            double.tryParse(_getData(2))?.toStringAsFixed(2) ?? 'N/A';
        final bool isComfortTrip = _getData(31) == 'Comfort';
        final String carType = _getData(31).tr;

        final String pickupName = _getData(12);
        final String pickupDetails = '(${_getData(11)})';
        final String pickupFullAddress = _getData(29);

        final String dropoffName = _getData(5);
        final String dropoffDetails = '(${_getData(4)})';
        final String dropoffFullAddress = _getData(30);

        final String passengerName = _getData(8);
        final String passengerRating = _getData(33);

        final bool isVisaPayment = _getData(13) == 'true';
        final bool hasSteps = _getData(20) == 'haveSteps';

        final String mapUrl =
            'https://www.google.com/maps/dir/${_getData(0)}/${_getData(1)}/';
        final String rideId = _getData(16); // Commonly used ID

        return Scaffold(
          appBar: appBar,
          backgroundColor: AppColor.secondaryColor ??
              Colors.grey[100], // Background for the page
          body: SafeArea(
            // Ensures content is not obscured by system UI
            child: Padding(
              padding:
                  bodyContentPadding, // Apply overall padding to the body's content area
              child: SizedBox(
                // Constrain the height of the main layout Column
                height: mainColumnHeight,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    // --- MAP SECTION ---
                    SizedBox(
                      height:
                          Get.height * 0.28, // Relative to total screen height
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(15.0),
                        child: GoogleMap(
                          initialCameraPosition: CameraPosition(
                              zoom: 12,
                              target:
                                  Get.find<HomeCaptainController>().myLocation),
                          cameraTargetBounds:
                              CameraTargetBounds(controller.bounds),
                          myLocationButtonEnabled: false,
                          trafficEnabled: false,
                          buildingsEnabled: false,
                          mapToolbarEnabled: false,
                          myLocationEnabled: true,
                          markers: {
                            Marker(
                                markerId: MarkerId('MyLocation'.tr),
                                position: LatLng(
                                    controller.latPassengerLocation,
                                    controller.lngPassengerLocation),
                                icon: controller.startIcon),
                            Marker(
                                markerId: MarkerId('Destination'.tr),
                                position: LatLng(
                                    controller.latPassengerDestination,
                                    controller.lngPassengerDestination),
                                icon: controller.endIcon),
                          },
                          polylines: {
                            Polyline(
                              zIndex: 1,
                              consumeTapEvents: true,
                              geodesic: true,
                              endCap: Cap.buttCap,
                              startCap: Cap.buttCap,
                              visible: true,
                              polylineId: const PolylineId('routeOrder'),
                              points: controller.pointsDirection,
                              color: AppColor.primaryColor,
                              width: 3,
                            ),
                          },
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),

                    // --- PRICE & TRIP TYPE SECTION ---
                    Card(
                      elevation: 3,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12)),
                      child: Padding(
                        padding: const EdgeInsets.symmetric(
                            vertical: 12.0, horizontal: 16.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              price,
                              style: AppStyle.headTitle.copyWith(
                                  color: AppColor.primaryColor,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 28),
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Text(
                                  carType,
                                  style: AppStyle.title.copyWith(
                                      color: AppColor.greenColor,
                                      fontWeight: FontWeight.bold),
                                ),
                                if (isComfortTrip)
                                  Row(
                                    children: [
                                      const Icon(Icons.ac_unit,
                                          color: AppColor.blueColor, size: 18),
                                      const SizedBox(width: 4),
                                      Text('Air condition Trip'.tr,
                                          style: AppStyle.subtitle
                                              .copyWith(fontSize: 13)),
                                    ],
                                  ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),

                    // --- EXPANDED SECTION FOR SCROLLABLE (BUT NOT USER-SCROLLABLE) CONTENT ---
                    Expanded(
                      child: SingleChildScrollView(
                        physics:
                            const NeverScrollableScrollPhysics(), // Prevents user scrolling
                        child: Column(
                          mainAxisSize: MainAxisSize
                              .min, // Takes minimum vertical space needed
                          children: [
                            _buildLocationCard(
                              icon: Icons.arrow_circle_up,
                              iconColor: AppColor.greenColor,
                              title: pickupName,
                              subtitle: pickupDetails,
                              fullAddress: pickupFullAddress,
                            ),
                            const SizedBox(height: 8),
                            _buildLocationCard(
                              icon: Icons.arrow_circle_down,
                              iconColor: AppColor.redColor,
                              title: dropoffName,
                              subtitle: dropoffDetails,
                              fullAddress: dropoffFullAddress,
                            ),
                            const SizedBox(height: 8),
                            // --- PAYMENT, STEPS & DIRECTIONS INFO ---
                            Card(
                              elevation: 2,
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10)),
                              child: Padding(
                                padding: const EdgeInsets.all(10.0),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        Icon(
                                          isVisaPayment
                                              ? Icons.credit_card
                                              : Icons
                                                  .payments_outlined, // Using payments_outlined for cash
                                          color: isVisaPayment
                                              ? AppColor.deepPurpleAccent
                                              : AppColor.greenColor,
                                          size: 24,
                                        ),
                                        const SizedBox(width: 8),
                                        Text(
                                          isVisaPayment ? 'Visa'.tr : 'Cash'.tr,
                                          style: AppStyle.title.copyWith(
                                              fontWeight: FontWeight.w600),
                                        ),
                                      ],
                                    ),
                                    if (hasSteps)
                                      Expanded(
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            const Icon(
                                                Icons
                                                    .format_list_numbered_rtl_outlined,
                                                color: AppColor.bronze,
                                                size: 24),
                                            const SizedBox(width: 4),
                                            Flexible(
                                                child: Text(
                                              'Trip has Steps'.tr,
                                              style: AppStyle.title.copyWith(
                                                  color: AppColor.bronze,
                                                  fontSize: 13),
                                              overflow: TextOverflow.ellipsis,
                                            )),
                                          ],
                                        ),
                                      ),
                                    TextButton.icon(
                                      style: TextButton.styleFrom(
                                        padding: EdgeInsets.zero,
                                        tapTargetSize:
                                            MaterialTapTargetSize.shrinkWrap,
                                        alignment: Alignment.centerRight,
                                      ),
                                      onPressed: () => showInBrowser(mapUrl),
                                      icon: const Icon(
                                          Icons.directions_outlined,
                                          color: AppColor.blueColor,
                                          size: 20),
                                      label: Text("Directions".tr,
                                          style: AppStyle.subtitle.copyWith(
                                              color: AppColor.blueColor,
                                              fontSize: 13)),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            const SizedBox(height: 8),
                            // --- PASSENGER INFO ---
                            Card(
                              elevation: 2,
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10)),
                              child: Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 16.0, vertical: 10.0),
                                child: Row(
                                  children: [
                                    const Icon(Icons.person_outline,
                                        color: AppColor.greyColor, size: 22),
                                    const SizedBox(width: 10),
                                    Expanded(
                                      child: Text(
                                        passengerName,
                                        style: AppStyle.title,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                    const SizedBox(width: 10),
                                    const Icon(Icons.star_rounded,
                                        color: Colors.amber, size: 20),
                                    Text(
                                      passengerRating,
                                      style: AppStyle.title.copyWith(
                                          fontWeight: FontWeight.bold),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    // const SizedBox(height: 8), // Spacer before action buttons if needed

                    // --- ACTION BUTTONS & TIMER ---
                    Padding(
                      padding: const EdgeInsets.only(top: 8.0, bottom: 5.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: MyElevatedButton(
                              kolor: AppColor.greenColor,
                              title: 'Accept Order'.tr,
                              onPressed: () async {
                                Get.put(HomeCaptainController()).changeRideId();
                                box.write(BoxName.statusDriverLocation, 'on');
                                var res = await CRUD().post(
                                    link: AppLink.updateStausFromSpeed,
                                    payload: {
                                      'id': rideId,
                                      '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': rideId,
                                        'rideTimeStart':
                                            DateTime.now().toString(),
                                        'status': 'Apply',
                                        'driver_id': box.read(BoxName.driverID),
                                      });
                                }
                                if (res != "failure") {
                                  box.write(BoxName.statusDriverLocation, 'on');
                                  controller.changeApplied();
                                  List<String> bodyToPassenger = [
                                    box.read(BoxName.driverID).toString(),
                                    box.read(BoxName.nameDriver).toString(),
                                    box.read(BoxName.tokenDriver).toString(),
                                    rideId.toString(),
                                  ];
                                  Get.put(FirebaseMessagesController())
                                      .sendNotificationToDriverMAP(
                                          'Accepted Ride',
                                          'your ride is applied'.tr,
                                          controller.arguments?['DriverList']
                                                      ?[9]
                                                  ?.toString() ??
                                              _getData(9), // Safer access
                                          bodyToPassenger,
                                          'start.wav');

                                  // Using rideId (_getData(16)) for order_id consistently
                                  CRUD().postFromDialogue(
                                      link: AppLink.addDriverOrder,
                                      payload: {
                                        'driver_id': _getData(
                                            6), // Driver ID from the order data
                                        'order_id': rideId,
                                        'status': 'Apply'
                                      });

                                  if (AppLink.endPoint !=
                                      AppLink.seferCairoServer) {
                                    CRUD().post(
                                        link:
                                            "${AppLink.endPoint}/ride/driver_order/add.php",
                                        payload: {
                                          'driver_id': _getData(6),
                                          'order_id': rideId,
                                          'status': 'Apply'
                                        });
                                  }

                                  Get.back(); // Go back from order request screen
                                  box.write(BoxName.rideArguments, {
                                    'passengerLocation': _getData(0),
                                    'passengerDestination': _getData(1),
                                    'Duration': _getData(4),
                                    'totalCost': _getData(26),
                                    'Distance': _getData(5),
                                    'name': _getData(8),
                                    'phone': _getData(10),
                                    'email': _getData(28),
                                    'WalletChecked': _getData(13),
                                    'tokenPassenger': _getData(9),
                                    'direction': mapUrl,
                                    'DurationToPassenger': _getData(15),
                                    'rideId': rideId,
                                    'passengerId': _getData(7),
                                    'driverId': box
                                        .read(BoxName.driverID)
                                        .toString(), // Current driver accepting
                                    'durationOfRideValue': _getData(19),
                                    'paymentAmount': _getData(2),
                                    'paymentMethod': _getData(13) == 'true'
                                        ? 'visa'
                                        : 'cash',
                                    'isHaveSteps': _getData(20),
                                    'step0': _getData(21),
                                    'step1': _getData(22),
                                    'step2': _getData(23),
                                    'step3': _getData(24),
                                    'step4': _getData(25),
                                    'passengerWalletBurc': _getData(26),
                                    'timeOfOrder': DateTime.now().toString(),
                                    'totalPassenger': _getData(
                                        2), // This is likely trip cost for passenger
                                    'carType': _getData(31),
                                    'kazan':
                                        _getData(32), // Driver's commission/cut
                                    'startNameLocation': _getData(29),
                                    'endNameLocation': _getData(30),
                                  });
                                  Get.to(() => PassengerLocationMapPage(),
                                      arguments:
                                          box.read(BoxName.rideArguments));
                                } else {
                                  Get.defaultDialog(
                                      title:
                                          "This ride is already taken by another driver."
                                              .tr,
                                      middleText: '',
                                      titleStyle: AppStyle.title,
                                      middleTextStyle: AppStyle.title,
                                      confirm: MyElevatedButton(
                                          title: 'Ok'.tr,
                                          onPressed: () {
                                            Get.back(); // Close dialog
                                            Get.back(); // Close order request screen
                                          }));
                                }
                              },
                            ),
                          ),
                          const SizedBox(width: 10),
                          // --- TIMER ---
                          GetBuilder<OrderRequestController>(
                            id: 'timerUpdate', // Ensure controller calls update(['timerUpdate']) for this
                            builder: (timerCtrl) {
                              final isNearEnd =
                                  timerCtrl.remainingTimeSpeed <= 5;
                              return SizedBox(
                                width: 60,
                                height: 60,
                                child: Stack(
                                  alignment: Alignment.center,
                                  children: [
                                    CircularProgressIndicator(
                                      value: timerCtrl.progressSpeed,
                                      color: isNearEnd
                                          ? Colors.redAccent
                                          : AppColor.primaryColor,
                                      strokeWidth: 5,
                                      backgroundColor: Colors.grey.shade300,
                                    ),
                                    Text('${timerCtrl.remainingTimeSpeed}',
                                        style: AppStyle.headTitle2.copyWith(
                                          color: isNearEnd
                                              ? Colors.redAccent
                                              : AppColor.writeColor ??
                                                  Colors.black,
                                        )),
                                  ],
                                ),
                              );
                            },
                          ),
                          const SizedBox(width: 10),
                          Expanded(
                            child: MyElevatedButton(
                              title: 'Refuse Order'.tr,
                              onPressed: () async {
                                controller.endTimer();
                                controller.refuseOrder(rideId);
                                controller.addRideToNotificationDriverString(
                                    rideId,
                                    _getData(29),
                                    _getData(30),
                                    '${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day}',
                                    '${DateTime.now().hour}:${DateTime.now().minute}',
                                    _getData(2),
                                    _getData(7),
                                    'wait',
                                    _getData(31),
                                    _getData(33),
                                    _getData(2),
                                    _getData(5),
                                    _getData(4));
                                // Get.back(); // refuseOrder or endTimer should handle navigation if needed.
                                // If not, add Get.back(); here.
                              },
                              kolor: AppColor.redColor,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  // Helper widget for location cards to reduce repetition and improve readability
  Widget _buildLocationCard(
      {required IconData icon,
      required Color iconColor,
      required String title,
      required String subtitle,
      required String fullAddress}) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      margin: const EdgeInsets.symmetric(
          vertical: 4), // Add a little vertical margin between cards
      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Icon(icon, color: iconColor, size: 28),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "$title $subtitle"
                        .trim(), // Trim to avoid extra spaces if subtitle is empty
                    style: AppStyle.title.copyWith(fontWeight: FontWeight.w600),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  if (fullAddress.isNotEmpty) ...[
                    const SizedBox(height: 3),
                    Text(
                      fullAddress,
                      style: AppStyle.subtitle
                          .copyWith(fontSize: 13, color: AppColor.greyColor),
                      maxLines: 2, // Allow up to 2 lines for address
                      overflow: TextOverflow.ellipsis,
                    ),
                  ]
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
