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 '../../widgets/custom_text_field.dart';
import '../../widgets/custom_text_itnerary_sub.dart';

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

  BusScreen({
    required this.onClose,
    this.apiData,
    required this.onSaveBus,
    required this.selectedItem,
    required this.loginUser,
  });

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

class _BusScreenState extends State<BusScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

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

  final FocusNode _tripTypeFocusNode = FocusNode();
  final FocusNode _hotelNameFocusNode = FocusNode();
  final FocusNode _fromFocusNode = FocusNode();
  final FocusNode _toFocusNode = FocusNode();
  final FocusNode _dateFocusNode = FocusNode();
  final FocusNode _timeFocusNode = FocusNode();
  final FocusNode _commentsFocusNode = FocusNode();

  late Map<String, TextEditingController> _controllers;
  Map<String, String> errorMessages = {};

  late TextEditingController _tripTypeController = TextEditingController();
  late TextEditingController _hotelNameController = TextEditingController();
  late TextEditingController _fromController = TextEditingController();
  late TextEditingController _toController = TextEditingController();
  late TextEditingController _dateController = TextEditingController();
  late TextEditingController _timeController = TextEditingController();
  late TextEditingController _buscommentsController = TextEditingController();

  bool _tripTypeFocused = false;
  bool _isHotelNameFocused = false;
  bool _fromFocus = false;
  bool _toFocus = false;
  bool _dateFocus = false;
  bool _timeFocus = false;
  bool _commentsFocus = false;

  Map<String, dynamic> get busData {
    Map<String, dynamic> data = {
      "from": _fromController.text,
      "to": _toController.text,
      "date": _dateController.text,
      "time": _timeController.text,
      "comments": _buscommentsController.text,
      "created_by": widget.loginUser,
      "updated_by": widget.loginUser,
    };

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

    return data;
  }

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

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

    _tripTypeFocusNode.addListener(() {
      setState(() {
        _tripTypeFocused = _tripTypeFocusNode.hasFocus;
      });
    });

    _hotelNameFocusNode.addListener(() {
      setState(() {
        _isHotelNameFocused = _hotelNameFocusNode.hasFocus;
      });
    });
    _fromFocusNode.addListener(() {
      setState(() {
        _fromFocus = _fromFocusNode.hasFocus;
      });
    });

    _toFocusNode.addListener(() {
      setState(() {
        _toFocus = _toFocusNode.hasFocus;
      });
    });
    _dateFocusNode.addListener(() {
      setState(() {
        _dateFocus = _dateFocusNode.hasFocus;
      });
    });

    _timeFocusNode.addListener(() {
      setState(() {
        _timeFocus = _timeFocusNode.hasFocus;
      });
    });

    _commentsFocusNode.addListener(() {
      setState(() {
        _commentsFocus = _commentsFocusNode.hasFocus;
      });
    });

    _buscommentsController = initController("comments");
    _fromController = initController("from");
    _toController = initController("to");
    _dateController = initController("date");
    _timeController = initController("time");

    _fromController.addListener(() => _clearError("from"));
    _toController.addListener(() => _clearError("to"));
    _dateController.addListener(() => _clearError("date"));
    _timeController.addListener(() => _clearError("time"));
  }

  @override
  void dispose() {
    _tripTypeFocusNode.dispose();
    _dateFocusNode.dispose();
    _timeFocusNode.dispose();

    _tripTypeController.dispose();
    _hotelNameController.dispose();
    _fromController.dispose();
    _toController.dispose();
    _dateController.dispose();
    _timeController.dispose();
    _buscommentsController.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 = ["from", "to", "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 accomadationData $busData");

    Map<String, dynamic> data = busData;

    if (!isValidData(data)) {
      print("Validation Failed: Required fields are missing.");
      setState(() {});
      return; // Stop execution if validation fails
    } else {
      widget.onSaveBus(busData);
    }
    widget.onClose("Bus", 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: Colors.white,
          child: Form(
            key: _formKey,
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                children: [
                  // Align(
                  //   alignment: Alignment.centerRight,
                  //   child: InkWell(
                  //     onTap: () {
                  //       widget.onClose(false);
                  //     },
                  //     child: Icon(
                  //       Icons.close,
                  //       size: 18,
                  //       color: Color(0xFF575A74),
                  //     ),
                  //   ),
                  // ),
                  // Text("Bus Booking List",
                  //     style: TextStyle(
                  //         fontSize: 18,
                  //         fontWeight: FontWeight.bold,
                  //         color: Color(0xFF575A74))),
                  // SizedBox(
                  //   height: 6,
                  // ),
                  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 [
      // ...buildResponsiveRow(_buildFirstRow(isDesktop)),

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

      ...buildResponsiveRow(_buildThirdRow(isDesktop)),

      // Actions row remains a Row
    ];
  }

  List<Widget> _buildFirstRow(isDesktop) {
    return [
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Trip Type",
            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),
    ];
  }

  List<Widget> _buildTripType(bool isDesktop) {
    List<dynamic> purposeList = widget.apiData?['flight_trip_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
    String? selectedPurpose =
        dropdownItems.isNotEmpty ? dropdownItems.first.value : null;

    return [
      CustomTextFieldWrapper(
        isFocused: _isHotelNameFocused,
        isDesktop: isDesktop,
        child: SizedBox(
          height: 40,
          child: DropdownButtonFormField<String>(
            focusNode: _tripTypeFocusNode, // Assign the correct focus node
            value: selectedPurpose,
            // style: TextStyle(fontSize: 12),
            style: GoogleFonts.poppins(fontSize: 12, color: Colors.black),
            decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: EdgeInsets.symmetric(
                horizontal: 10,
              ), // Proper padding
            ),
            onChanged:
                purposeList.isNotEmpty
                    ? (newValue) {
                      setState(() {
                        selectedPurpose = newValue;
                      });
                      print(
                        "Updating form data: Flight -> trip_type -> ${newValue ?? ""}",
                      );
                    }
                    : null,

            items: dropdownItems,
          ),
        ),
      ),
    ];
  }

  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.";
          });
          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,
              ),
            );
            _timeController.text = formattedTime;
          });
        }
      }
    }

    return [
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "From *",
            style: GoogleFonts.poppins(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFF575A74),
            ),
          ),
          SizedBox(height: 5),
          CustomTextFieldItnerarySubWrapper(
            isFocused: _fromFocus,
            isDesktop: isDesktop,
            child: SizedBox(
              height: 40,
              child: TextField(
                focusNode: _fromFocusNode,
                controller: _fromController,
                style: const TextStyle(fontSize: 12),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9 _-]')),
                ],
                decoration: const InputDecoration(
                  labelText: "From",
                  labelStyle: TextStyle(fontSize: 12, color: Colors.grey),
                  floatingLabelBehavior: FloatingLabelBehavior.never,
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(vertical: 16),
                ),
              ),
            ),
          ),
          if (errorMessages["from"] != 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(
            "To *",
            style: GoogleFonts.poppins(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFF575A74),
            ),
          ),
          SizedBox(height: 5),
          CustomTextFieldItnerarySubWrapper(
            isFocused: _toFocus,
            isDesktop: isDesktop,
            child: SizedBox(
              height: 40,
              child: TextField(
                focusNode: _toFocusNode,
                controller: _toController,
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9 _-]')),
                ],
                style: const TextStyle(fontSize: 12),
                decoration: const InputDecoration(
                  labelText: "To",
                  labelStyle: TextStyle(fontSize: 12, color: Colors.grey),
                  floatingLabelBehavior: FloatingLabelBehavior.never,
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(vertical: 16),
                ),
              ),
            ),
          ),
          if (errorMessages["to"] != 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,

                    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: () {
                  // _selectedCheckOutTime = null; // ✅ Reset time variable
                  _timeController.text = ""; // ✅ Clear text field
                  _timeFocusNode.requestFocus();
                  _selectCheckOutTime(context);
                },
                child: AbsorbPointer(
                  child: TextField(
                    focusNode: _timeFocusNode,
                    controller: _timeController,
                    readOnly: true,
                    style: const TextStyle(fontSize: 12, color: Colors.black),
                    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(
              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,
            child: SizedBox(
              height: 40,
              child: TextField(
                focusNode: _commentsFocusNode,
                controller: _buscommentsController,
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9 _-]')),
                ],
                style: TextStyle(fontSize: 12),
                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(),
      Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: _handleAction(isDesktop),
          ),
        ],
      ),
    ];
  }

  List<Widget> _handleAction(bool isDesktop) {
    return [
      // Close Button
      ElevatedButton(
        onPressed: () {
          widget.onClose("Bus", false);
          // widget.onClose(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),
        ),
      ),
    ];
  }
}
