import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:responsive_builder/responsive_builder.dart';

import '../../utils/auth_utils.dart';
import '../../widgets/custom_text_field.dart';
import '../../widgets/custom_text_itnerary_sub.dart';

class TaxiScreen extends StatefulWidget {
  final Map<String, dynamic>? apiData;
  final Function(String, bool) onClose;
  final Function(Map<String, dynamic>) onSavetaxi;
  final Map<String, dynamic>? selectedItem;
  final String? loginUser;

  TaxiScreen({
    required this.onClose,
    this.apiData,
    required this.onSavetaxi,
    required this.selectedItem,
    required this.loginUser,
  });

  @override
  _TaxiScreenState createState() => _TaxiScreenState();
}

class _TaxiScreenState extends State<TaxiScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  Map<String, String?> selectedValues = {};
  Map<String, String> errorMessages = {};

  final FocusNode _destinationFocusNode = FocusNode();
  final FocusNode _locationFocusNode = FocusNode();
  final FocusNode _taxiReqFocusNode = FocusNode();
  final FocusNode _toFocusNode = FocusNode();
  final FocusNode _dateFocusNode = FocusNode();
  final FocusNode _timeFocusNode = FocusNode();
  final FocusNode _numPassengerFocusNode = FocusNode();
  final FocusNode _commentsFocusNode = FocusNode();
  final FocusNode _carTypeFocusNode = FocusNode();

  late TextEditingController _destinationController = TextEditingController();
  late TextEditingController _locationController = TextEditingController();
  late TextEditingController _dateController = TextEditingController();
  late TextEditingController _timeController = TextEditingController();
  late TextEditingController _numPassengerController = TextEditingController();
  late TextEditingController _taxiCommentsController = TextEditingController();

  bool _destinationFocus = false;
  bool _locationFocus = false;
  bool _toFocus = false;
  bool _dateFocus = false;
  bool _taxiReqFocused = false;
  bool _carTypeFocused = false;
  bool _numPassengerFocus = false;
  bool _timeFocus = false;
  bool _commentsFocus = false;

  String? selectedReqTaxi;
  String? selectedCarType;
  Color layoutColor = Colors.grey;

  Map<String, dynamic> get taxiData {
    Map<String, dynamic> data = {
      "destination_city": _destinationController.text,
      "date": _dateController.text,
      "time": _timeController.text,
      "location_of_pickup": _locationController.text,
      "car_required_for": selectedReqTaxi,
      "no_of_passengers": _numPassengerController.text,
      "car_type": selectedCarType,
      "comments": _taxiCommentsController.text,
      "created_by": widget.loginUser,
      "updated_by": widget.loginUser,
      // "updated_on": ,
      // "updated_by": ,
    };

    if (widget.selectedItem != null) {
      if (widget.selectedItem?["indx"] != null &&
          widget.selectedItem?["indx"] != 0) {
        data["indx"] = widget.selectedItem!["indx"];
      } else if (widget.selectedItem?["taxi_id"] != null &&
          widget.selectedItem?["taxi_id"] != 0) {
        data["taxi_id"] = widget.selectedItem!["taxi_id"];
      }
    }

    return data;
  }

  TextEditingController initController(String key) {
    return TextEditingController(text: widget.selectedItem?[key] ?? "");
  }

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      loadInitialData();
    });

    _addFocusListener(
      _destinationFocusNode,
      (focus) => _destinationFocus = focus,
    );
    _addFocusListener(_locationFocusNode, (focus) => _locationFocus = focus);
    _addFocusListener(_dateFocusNode, (focus) => _dateFocus = focus);
    _addFocusListener(_timeFocusNode, (focus) => _timeFocus = focus);
    _addFocusListener(_taxiReqFocusNode, (focus) => _taxiReqFocused = focus);
    _addFocusListener(_carTypeFocusNode, (focus) => _carTypeFocused = focus);
    _addFocusListener(
      _numPassengerFocusNode,
      (focus) => _numPassengerFocus = focus,
    );
    _addFocusListener(_commentsFocusNode, (focus) => _commentsFocus = focus);

    _destinationController = initController("destination_city");
    _dateController = initController("date");
    _timeController = initController("time");
    _locationController = initController("location_of_pickup");
    _numPassengerController = initController("no_of_passengers");
    _taxiCommentsController = initController("comments");

    // Set the selected value if available
    if (widget.selectedItem != null &&
        widget.selectedItem!["car_required_for"] != null) {
      selectedReqTaxi = widget.selectedItem!["car_required_for"].toString();
    }

    // Set the selected value if available
    if (widget.selectedItem != null &&
        widget.selectedItem!["car_type"] != null) {
      selectedCarType = widget.selectedItem!["car_type"].toString();
    }

    _destinationController.addListener(() => _clearError("destination_city"));
    _locationController.addListener(() => _clearError("location_of_pickup"));
    _dateController.addListener(() => _clearError("date"));
    _timeController.addListener(() => _clearError("time"));
    _numPassengerController.addListener(() => _clearError("no_of_passengers"));
  }

  void _addFocusListener(FocusNode node, Function(bool) updateState) {
    node.addListener(() {
      setState(() {
        updateState(node.hasFocus);
      });
    });
  }

  void loadInitialData() async {
    String? layoutString = await getLayoutColor();

    setState(() {
      layoutColor =
          layoutString != null
              ? Color(int.parse(layoutString))
              : Colors.redAccent;
    });
  }

  @override
  void dispose() {
    _destinationFocusNode.dispose();
    _locationFocusNode.dispose();
    _carTypeFocusNode.dispose();
    _destinationController.dispose();
    _dateController.dispose();
    _timeController.dispose();
    _taxiCommentsController.dispose();
    super.dispose();
  }

  void _clearError(String field) {
    if (mounted && errorMessages.containsKey(field)) {
      setState(() {
        errorMessages.remove(field);
      });
    }
  }

  bool isValidData(Map<String, dynamic> data) {
    errorMessages.clear(); // Reset errors

    // Required fields that must not be empty
    List<String> requiredFields = [
      "destination_city",
      "location_of_pickup",
      "no_of_passengers",
      "date",
      "time",
    ];

    // Check validation for each field
    for (String field in requiredFields) {
      if (data[field] == null || data[field].toString().trim().isEmpty) {
        errorMessages[field] = "Required";
      }
    }

    return errorMessages.isEmpty; // Valid if there are no errors
  }

  void handleSave() {
    print("Handle Save taxiData $taxiData");

    Map<String, dynamic> data = taxiData;

    if (!isValidData(data)) {
      print("Validation Failed: Required fields are missing.");
      setState(() {});
      return; // Stop execution if validation fails
    } else {
      widget.onSavetaxi(taxiData);
    }
    widget.onClose("Taxi", false);
    // widget.onClose(false); // Close screen after saving
  }

  @override
  Widget build(BuildContext context) {
    return ResponsiveBuilder(
      builder: (context, sizingInfo) {
        bool isMobile = sizingInfo.isMobile;
        bool isDesktop =
            sizingInfo.deviceScreenType == DeviceScreenType.desktop;

        return Container(
          // color: Color(0xFFF4F4FB),
          child: Form(
            key: _formKey,
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.only(top: 30.0),
                    child: Center(
                      child: Column(children: _buildAccomadtionForm(isDesktop)),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  List<Widget> _buildAccomadtionForm(bool isDesktop) {
    List<Widget> buildResponsiveRow(List<Widget> children) {
      return [
        isDesktop ? Row(children: children) : Column(children: children),
        SizedBox(height: 10),
      ];
    }

    List<List<Widget>> rowBuilders = [
      // _builClassType(isDesktop),
      _buildSecondRow(isDesktop),
    ];

    return [
      // Iterate over rowBuilders and wrap each in a responsive container
      ...rowBuilders.expand((row) => buildResponsiveRow(row)),

      ...buildResponsiveRow(_buildFirstRow(isDesktop)),

      ...buildResponsiveRow(_buildThirdRow(isDesktop)),

      // Actions row remains a Row
    ];
  }

  List<Widget> _buildFirstRow(isDesktop) {
    List<dynamic> purposeList = widget.apiData?['taxt_car_type'] ?? [];

    List<DropdownMenuItem<String>> dropdownItems =
        purposeList
            .map(
              (item) => DropdownMenuItem<String>(
                value: item['dropdown_key'],
                child: Text(item['dropdown_value']),
              ),
            )
            .toList();

    if (dropdownItems.isEmpty) {
      dropdownItems.add(
        DropdownMenuItem<String>(
          value: null,
          child: Text(
            "No options available",
            style: TextStyle(color: Colors.grey),
          ),
        ),
      );
    }

    // Default selected value
    selectedCarType ??=
        dropdownItems.isNotEmpty ? dropdownItems.first.value : null;

    return [
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Taxi Required For",
            style: GoogleFonts.poppins(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFF575A74),
            ),
          ),
          SizedBox(height: 5),
          isDesktop
              ? Row(children: _buildTripType(isDesktop))
              : Column(children: _buildTripType(isDesktop)),
        ],
      ),
      if (isDesktop) Spacer() else SizedBox(height: 8),
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Number of Passenger *",
            style: GoogleFonts.poppins(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFF575A74),
            ),
          ),
          SizedBox(height: 5),
          CustomTextFieldItnerarySubWrapper(
            isFocused: _numPassengerFocus,
            isDesktop: isDesktop,
            child: SizedBox(
              height: 40,
              child: TextField(
                focusNode: _numPassengerFocusNode,
                controller: _numPassengerController,

                style: const TextStyle(fontSize: 12),
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(
                    RegExp(r'^\d*\.?\d*$'),
                  ), // Allow only positive numbers with optional decimal
                ],
                decoration: const InputDecoration(
                  labelText: "Number of Passenger",
                  labelStyle: TextStyle(fontSize: 12, color: Colors.grey),
                  floatingLabelBehavior: FloatingLabelBehavior.never,
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(vertical: 16),
                ),
              ),
            ),
          ),
          if (errorMessages["no_of_passengers"] != null) ...[
            SizedBox(height: 5), // Space before error message
            Text("Required", style: TextStyle(color: Colors.red, fontSize: 12)),
          ],
        ],
      ),
      if (isDesktop) Spacer() else SizedBox(height: 8),
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Car Type",
            style: GoogleFonts.poppins(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFF575A74),
            ),
          ),
          SizedBox(height: 5),
          // CustomTextFieldItnerarySubWrapper(
          //   isFocused: _toFocus,
          //   isDesktop: isDesktop,
          //   child: SizedBox(
          //     height: 40,
          //     child: DropdownButtonFormField<String>(
          //       focusNode: _toFocusNode, // Assign the correct focus node
          //       value: selectedCarType,
          //       style: TextStyle(fontSize: 12),
          //       decoration: InputDecoration(
          //         border: InputBorder.none,
          //         contentPadding: EdgeInsets.symmetric(
          //           horizontal: 10,
          //         ), // Proper padding
          //       ),
          //       onChanged:
          //           purposeList.isNotEmpty
          //               ? (newValue) {
          //                 setState(() {
          //                   selectedCarType = newValue;
          //                 });
          //                 print(
          //                   "Updating form data: Flight -> trip_type -> ${newValue ?? ""}",
          //                 );
          //               }
          //               : null,
          //
          //       items: dropdownItems,
          //     ),
          //   ),
          // ),
          CustomTextFieldItnerarySubWrapper(
            isFocused: _toFocus,
            isDesktop: isDesktop,
            padding: const EdgeInsets.symmetric(horizontal: 0),
            child: SizedBox(
              height: 40,
              width: double.infinity,
              child: Focus(
                focusNode: _carTypeFocusNode,
                onFocusChange: (hasFocus) {
                  setState(() {
                    _carTypeFocused = hasFocus;
                  });
                },
                child: GestureDetector(
                  onTap: () {
                    // Request focus when user taps
                    _carTypeFocusNode?.requestFocus();
                  },
                  child: DropdownSearch<Map<String, dynamic>>(
                    // focusNode: _taxiReqFocusNode,
                    items: purposeList.cast<Map<String, dynamic>>(),
                    selectedItem: purposeList.firstWhere(
                      (item) => item['dropdown_key'] == selectedCarType,
                      orElse: () => {},
                    ),
                    itemAsString: (item) => item['dropdown_value'] ?? '',
                    popupProps: PopupProps.menu(
                      showSearchBox: false,
                      fit: FlexFit.loose,
                      menuProps: const MenuProps(backgroundColor: Colors.white),
                      itemBuilder: (context, item, isSelected) {
                        return Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 5,
                          ),
                          child: Text(
                            item['dropdown_value'] ?? '',
                            style: GoogleFonts.poppins(
                              fontSize: 12,
                              color: Colors.black,
                            ),
                          ),
                        );
                      },
                    ),
                    dropdownDecoratorProps: DropDownDecoratorProps(
                      dropdownSearchDecoration: InputDecoration(
                        // border: InputBorder.none,
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide(
                            color:
                                (_carTypeFocused ?? false)
                                    ? layoutColor!
                                    : Colors.white,
                            width: 1,
                          ),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color:
                                (_carTypeFocused ?? false)
                                    ? layoutColor
                                    : Colors.white,
                            // : const Color(0xFFD6D5E6),
                            width: 1,
                            // const Color(0xFFD6D5E6),
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: layoutColor, width: 1),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 10,
                        ),
                      ),
                    ),
                    dropdownBuilder: (context, selectedItem) {
                      if (selectedItem == null || selectedItem.isEmpty) {
                        return Text(
                          "Select ",
                          style: GoogleFonts.poppins(
                            color: Colors.grey,
                            fontSize: 13,
                          ),
                        );
                      }
                      return Text(
                        selectedItem['dropdown_value'] ?? '',
                        style: GoogleFonts.poppins(
                          fontSize: 12,
                          color: Colors.black,
                        ),
                      );
                    },
                    onChanged:
                        purposeList.isNotEmpty
                            ? (newValue) {
                              setState(() {
                                selectedCarType = newValue as String?;
                              });
                              print(
                                "Updating form data:  -> ${newValue ?? ""}",
                              );
                            }
                            : null,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
      if (isDesktop) SizedBox.shrink() else SizedBox(height: 8),
    ];
  }

  List<Widget> _buildTripType(bool isDesktop) {
    List<dynamic> purposeList = widget.apiData?['taxi_car_required_for'] ?? [];

    List<DropdownMenuItem<String>> dropdownItems =
        purposeList
            .map(
              (item) => DropdownMenuItem<String>(
                value: item['dropdown_key'],
                child: Text(item['dropdown_value']),
              ),
            )
            .toList();

    if (dropdownItems.isEmpty) {
      dropdownItems.add(
        DropdownMenuItem<String>(
          value: null,
          child: Text(
            "No options available",
            style: TextStyle(color: Colors.grey),
          ),
        ),
      );
    }

    // Default selected value
    selectedReqTaxi ??=
        dropdownItems.isNotEmpty ? dropdownItems.first.value : null;

    return [
      // CustomTextFieldWrapper(
      //   isFocused: _taxiReqFocused,
      //   isDesktop: isDesktop,
      //   width:
      //       isDesktop
      //           ? MediaQuery.of(context).size.width * 0.34
      //           : MediaQuery.of(context).size.width * 0.66,
      //   child: SizedBox(
      //     height: 40,
      //     child: DropdownButtonFormField<String>(
      //       focusNode: _taxiReqFocusNode, // Assign the correct focus node
      //       value: selectedReqTaxi,
      //       style: TextStyle(fontSize: 12),
      //       decoration: InputDecoration(
      //         border: InputBorder.none,
      //         contentPadding: EdgeInsets.symmetric(
      //           horizontal: 10,
      //         ), // Proper padding
      //       ),
      //       onChanged:
      //           purposeList.isNotEmpty
      //               ? (newValue) {
      //                 setState(() {
      //                   selectedReqTaxi = newValue;
      //                 });
      //                 print(
      //                   "Updating form data: Flight -> trip_type -> ${newValue ?? ""}",
      //                 );
      //               }
      //               : null,
      //
      //       items: dropdownItems,
      //     ),
      //   ),
      // ),
      CustomTextFieldItnerarySubWrapper(
        isFocused: _taxiReqFocused,
        isDesktop: isDesktop,
        padding: const EdgeInsets.symmetric(horizontal: 0),
        width:
            isDesktop
                ? MediaQuery.of(context).size.width * 0.35
                : null, //MediaQuery.of(context).size.width * 0.66,
        child: SizedBox(
          height: 40,
          width: double.infinity,
          child: Focus(
            focusNode: _taxiReqFocusNode,
            onFocusChange: (hasFocus) {
              setState(() {
                _taxiReqFocused = hasFocus;
              });
            },
            child: GestureDetector(
              onTap: () {
                _taxiReqFocusNode?.requestFocus();
              },
              child: DropdownSearch<Map<String, dynamic>>(
                // focusNode: _taxiReqFocusNode,
                items: purposeList.cast<Map<String, dynamic>>(),
                selectedItem: purposeList.firstWhere(
                  (item) => item['dropdown_key'] == selectedReqTaxi,
                  orElse: () => {},
                ),
                itemAsString: (item) => item['dropdown_value'] ?? '',
                popupProps: PopupProps.menu(
                  showSearchBox: false,
                  fit: FlexFit.loose,
                  menuProps: const MenuProps(backgroundColor: Colors.white),
                  itemBuilder: (context, item, isSelected) {
                    return Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 5,
                      ),
                      child: Text(
                        item['dropdown_value'] ?? '',
                        style: GoogleFonts.poppins(
                          fontSize: 12,
                          color: Colors.black,
                        ),
                      ),
                    );
                  },
                ),
                dropdownDecoratorProps: DropDownDecoratorProps(
                  dropdownSearchDecoration: InputDecoration(
                    // border: InputBorder.none,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: BorderSide(
                        color:
                            (_taxiReqFocused ?? false)
                                ? layoutColor!
                                : Colors.white,
                        width: 1,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                        color:
                            (_taxiReqFocused ?? false)
                                ? layoutColor
                                : Colors.white,
                        // : const Color(0xFFD6D5E6),
                        width: 1,
                        // const Color(0xFFD6D5E6),
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: layoutColor, width: 1),
                    ),
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 10,
                      vertical: 1,
                    ),
                  ),
                ),
                dropdownBuilder: (context, selectedItem) {
                  if (selectedItem == null || selectedItem.isEmpty) {
                    return Text(
                      "Select ",
                      style: GoogleFonts.poppins(
                        color: Colors.grey,
                        fontSize: 13,
                      ),
                    );
                  }
                  return Text(
                    selectedItem['dropdown_value'] ?? '',
                    style: GoogleFonts.poppins(
                      fontSize: 12,
                      color: Colors.black,
                    ),
                  );
                },
                onChanged:
                    purposeList.isNotEmpty
                        ? (newValue) {
                          setState(() {
                            selectedReqTaxi = newValue as String?;
                          });
                          print("Updating form data:  -> ${newValue ?? ""}");
                        }
                        : null,
              ),
            ),
          ),
        ),
      ),
    ];
  }

  List<Widget> _buildSecondRow(bool isDesktop) {
    DateTime? _selectedCheckOutDate;
    TimeOfDay? _selectedCheckOutTime;

    Future<void> _selectCheckOutDate(BuildContext context) async {
      DateTime now = DateTime.now();
      DateTime today = DateTime(now.year, now.month, now.day);

      DateTime? pickedDate = await showDatePicker(
        context: context,
        initialDate:
            _selectedCheckOutDate != null &&
                    _selectedCheckOutDate!.isAfter(today)
                ? _selectedCheckOutDate!
                : today,
        firstDate: today,
        lastDate: DateTime(2100),
        initialEntryMode: DatePickerEntryMode.calendarOnly,
      );

      if (pickedDate != null && pickedDate != _selectedCheckOutDate) {
        setState(() {
          _selectedCheckOutDate = pickedDate;
          _dateController.text = DateFormat('dd-MM-yyyy').format(pickedDate);
        });
      }
    }

    Future<void> _selectCheckOutTime(BuildContext context) async {
      TimeOfDay? pickedTime = await showTimePicker(
        context: context,
        initialTime: _selectedCheckOutTime ?? TimeOfDay.now(),
      );

      if (pickedTime != null && pickedTime != _selectedCheckOutTime) {
        // Parse the selected date
        final dateText = _dateController.text ?? "";
        final selectedDate = DateFormat(
          'dd-MM-yyyy',
        ).parse(dateText); // or 'yyyy-MM-dd' depending on your format
        final now = DateTime.now();

        final selectedDateTime = DateTime(
          selectedDate.year,
          selectedDate.month,
          selectedDate.day,
          pickedTime.hour,
          pickedTime.minute,
        );

        final isToday =
            selectedDate.year == now.year &&
            selectedDate.month == now.month &&
            selectedDate.day == now.day;

        bool isPastTime = selectedDateTime.isBefore(now);

        if (isToday && isPastTime) {
          setState(() {
            errorMessages["time"] = "You can't select a past time.";
            _selectedCheckOutTime = null; // ✅ Reset time variable
            _timeController.text = ""; // ✅ Clear text field
          });
          return;
        } else {
          setState(() {
            _selectedCheckOutTime = pickedTime;
            // Formatting time to HH:mm (24-hour format)
            final now = DateTime.now();
            final formattedTime = DateFormat('HH:mm').format(
              DateTime(
                now.year,
                now.month,
                now.day,
                pickedTime.hour,
                pickedTime.minute,
              ),
            );
            errorMessages["time"] = "";
            _timeController.text = formattedTime;
          });
        }
      }
    }

    // Future<void> _selectCheckOutTime(BuildContext context) async {
    //   TimeOfDay? pickedTime = await showTimePicker(
    //     context: context,
    //     initialTime: _selectedCheckOutTime ?? TimeOfDay.now(),
    //   );
    //
    //   if (pickedTime != null && pickedTime != _selectedCheckOutTime) {
    //     setState(() {
    //       _selectedCheckOutTime = pickedTime;
    //       // Formatting time to HH:mm (24-hour format)
    //       final now = DateTime.now();
    //       final formattedTime = DateFormat('HH:mm').format(
    //         DateTime(
    //           now.year,
    //           now.month,
    //           now.day,
    //           pickedTime.hour,
    //           pickedTime.minute,
    //         ),
    //       );
    //       _timeController.text = formattedTime;
    //     });
    //   }
    // }

    return [
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "City *",
            style: GoogleFonts.poppins(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFF575A74),
            ),
          ),
          SizedBox(height: 5),
          CustomTextFieldItnerarySubWrapper(
            isFocused: _destinationFocus,
            isDesktop: isDesktop,
            child: SizedBox(
              height: 40,
              child: TextField(
                focusNode: _destinationFocusNode,
                controller: _destinationController,
                style: const TextStyle(fontSize: 12),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9 _-]')),
                ],
                decoration: const InputDecoration(
                  labelText: "Destination",
                  labelStyle: TextStyle(fontSize: 12, color: Colors.grey),
                  floatingLabelBehavior: FloatingLabelBehavior.never,
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(vertical: 16),
                ),
              ),
            ),
          ),
          if (errorMessages["destination_city"] != null) ...[
            SizedBox(height: 5), // Space before error message
            Text("Required", style: TextStyle(color: Colors.red, fontSize: 12)),
          ],
        ],
      ),
      if (isDesktop) Spacer() else SizedBox(height: 8),
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Pickup Location *",
            style: GoogleFonts.poppins(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFF575A74),
            ),
          ),
          SizedBox(height: 5),
          CustomTextFieldItnerarySubWrapper(
            isFocused: _locationFocus,
            isDesktop: isDesktop,
            child: SizedBox(
              height: 40,
              child: TextField(
                focusNode: _locationFocusNode,
                controller: _locationController,
                style: const TextStyle(fontSize: 12),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9 _-]')),
                ],
                decoration: const InputDecoration(
                  labelText: "Pickup Location",
                  labelStyle: TextStyle(fontSize: 12, color: Colors.grey),
                  floatingLabelBehavior: FloatingLabelBehavior.never,
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(vertical: 16),
                ),
              ),
            ),
          ),
          if (errorMessages["location_of_pickup"] != null) ...[
            SizedBox(height: 5), // Space before error message
            Text("Required", style: TextStyle(color: Colors.red, fontSize: 12)),
          ],
        ],
      ),
      if (isDesktop) Spacer() else SizedBox(height: 8),
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Date *",
            style: GoogleFonts.poppins(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFF575A74),
            ),
          ),
          SizedBox(height: 5),
          CustomTextFieldItnerarySubWrapper(
            isFocused: _dateFocus,
            isDesktop: isDesktop,
            child: SizedBox(
              height: 40,
              child: GestureDetector(
                // onTap: () => _selectCheckOutDate(context),
                onTap: () {
                  _dateFocusNode.requestFocus();
                  _selectCheckOutDate(context);
                },
                child: AbsorbPointer(
                  child: TextField(
                    focusNode: _dateFocusNode,
                    controller: _dateController,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(
                        RegExp(r'[a-zA-Z0-9 _-]'),
                      ),
                    ],
                    readOnly: true,
                    style: const TextStyle(fontSize: 12),
                    decoration: const InputDecoration(
                      labelText: "Select Date",
                      labelStyle: TextStyle(fontSize: 12, color: Colors.grey),
                      floatingLabelBehavior: FloatingLabelBehavior.never,
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 16),
                      suffixIcon: Icon(
                        Icons.calendar_today,
                        size: 16,
                        color: Colors.grey,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
          if (errorMessages["date"] != null) ...[
            SizedBox(height: 5), // Space before error message
            Text("Required", style: TextStyle(color: Colors.red, fontSize: 12)),
          ],
        ],
      ),
      if (isDesktop) Spacer() else SizedBox(height: 8),
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Time *",
            style: GoogleFonts.poppins(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFF575A74),
            ),
          ),
          SizedBox(height: 5),
          CustomTextFieldItnerarySubWrapper(
            isFocused: _timeFocus,
            isDesktop: isDesktop,
            child: SizedBox(
              height: 40,
              child: GestureDetector(
                onTap: () {
                  _timeController.text = "";
                  _timeFocusNode.requestFocus();
                  _selectCheckOutTime(context);
                },
                child: AbsorbPointer(
                  child: TextField(
                    focusNode: _timeFocusNode,
                    controller: _timeController,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(
                        RegExp(r'[a-zA-Z0-9 _-]'),
                      ),
                    ],
                    readOnly: true,
                    style: const TextStyle(fontSize: 12),
                    decoration: const InputDecoration(
                      labelText: "Select Time",
                      labelStyle: TextStyle(fontSize: 12, color: Colors.grey),
                      floatingLabelBehavior: FloatingLabelBehavior.never,
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 16),
                      suffixIcon: Icon(
                        Icons.access_time,
                        size: 16,
                        color: Colors.grey,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
          if (errorMessages["time"] != null) ...[
            SizedBox(height: 5), // Space before error message
            // Text("Required", style: TextStyle(color: Colors.red, fontSize: 12)),
            Text(
              errorMessages["time"]!,
              style: TextStyle(color: Colors.red, fontSize: 12),
            ),
          ],
        ],
      ),
    ];
  }

  List<Widget> _buildThirdRow(bool isDesktop) {
    return [
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Comments",
            style: GoogleFonts.poppins(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFF575A74),
            ),
          ),
          SizedBox(height: 5),
          CustomTextFieldItnerarySubWrapper(
            isFocused: _commentsFocus, // Dropdown doesn't use focus
            isDesktop: isDesktop,
            width:
                isDesktop
                    ? MediaQuery.of(context).size.width * 0.35
                    : null, //MediaQuery.of(context).size.width * 0.66,

            child: SizedBox(
              height: 40,
              child: TextField(
                focusNode: _commentsFocusNode,
                controller: _taxiCommentsController,
                style: TextStyle(fontSize: 12),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9 _-]')),
                ],
                decoration: InputDecoration(
                  labelText: "Comments",
                  labelStyle: TextStyle(fontSize: 12, color: Colors.grey),
                  floatingLabelBehavior: FloatingLabelBehavior.never,
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(vertical: 16),
                ),
              ),
            ),
          ),
        ],
      ),
      if (isDesktop) Spacer(),
      SizedBox(height: 5),
      Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: _handleAction(isDesktop),
          ),
        ],
      ),
    ];
  }

  List<Widget> _handleAction(bool isDesktop) {
    return [
      // Close Button
      ElevatedButton(
        onPressed: () {
          widget.onClose("Taxi", false); // Close the dialog or screen
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.grey[400], // Light grey color
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
        ),
        child: Text(
          "Close",
          style: GoogleFonts.poppins(color: Colors.white, fontSize: 12),
        ),
      ),
      SizedBox(width: 10), // Space between buttons
      // Save Changes Button
      ElevatedButton(
        onPressed: () {
          handleSave();
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: Color(0xFF114D8B), // Primary color for save
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
        ),
        child: Text(
          "Save Changes",
          style: GoogleFonts.poppins(color: Colors.white, fontSize: 12),
        ),
      ),
    ];
  }
}
