import 'package:flutter/material.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 TrainScreen extends StatefulWidget { final Map? apiData; final Function(Map)onSavetrain; final Function(bool) onClose; final Map? selectedItem; final String? loginUser; TrainScreen({ required this.onClose, this.apiData, required this.onSavetrain, required this.selectedItem, required this.loginUser}); @override _TrainScreenState createState() => _TrainScreenState(); } class _TrainScreenState extends State { final GlobalKey _formKey = GlobalKey(); Map selectedValues = {}; final FocusNode _trainNoFocusNode = 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 TextEditingController _trainNoController = TextEditingController(); late TextEditingController _hotelNameController = TextEditingController(); late TextEditingController _fromController = TextEditingController(); late TextEditingController _toController = TextEditingController(); late TextEditingController _dateController = TextEditingController(); late TextEditingController _timeController = TextEditingController(); late TextEditingController _trainCommentsController = TextEditingController(); bool _trainNoFocused = false; bool _isHotelNameFocused = false; bool _fromFocus = false; bool _toFocus = false; bool _dateFocus = false; bool _timeFocus = false; bool _commentsFocus = false; String? selectedClass; Map errorMessages = {}; Map get trainData { Map data ={ "train_no": _trainNoController.text, "class": selectedClass, "from_station": _fromController.text, "to_station": _toController.text, "date": _dateController.text, "time": _timeController.text, "comments": _trainCommentsController.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?["train_id"] != null && widget.selectedItem?["train_id"] != 0) { data["train_id"] = widget.selectedItem!["train_id"]; } } return data; } TextEditingController initController(String key) { return TextEditingController(text: widget.selectedItem?[key] ?? ""); } @override void initState() { super.initState(); _trainNoFocusNode.addListener(() { setState(() { _trainNoFocused = _trainNoFocusNode.hasFocus; }); }); _hotelNameFocusNode.addListener(() { setState(() { _isHotelNameFocused = _hotelNameFocusNode.hasFocus; }); }); _fromFocusNode.addListener(() { setState(() { _fromFocus = _fromFocusNode.hasFocus; }); }); _toFocusNode.addListener(() { setState(() { _toFocus = _toFocusNode.hasFocus; }); }); _dateFocusNode.addListener(() { setState(() { _dateFocus = _fromFocusNode.hasFocus; }); }); _timeFocusNode.addListener(() { setState(() { _timeFocus = _timeFocusNode.hasFocus; }); }); _commentsFocusNode.addListener(() { setState(() { _commentsFocus = _commentsFocusNode.hasFocus; }); }); _trainCommentsController = initController("comments"); _trainNoController = initController("train_no"); _fromController = initController("from_station"); _toController = initController("to_station"); _dateController = initController("date"); _timeController = initController("time"); // Set the selected value if available if (widget.selectedItem != null && widget.selectedItem!["class"] != null) { selectedClass = widget.selectedItem!["class"].toString(); } _trainNoController.addListener(() => _clearError("train_no")); _fromController.addListener(() => _clearError("from_station")); _toController.addListener(() => _clearError("to_station")); _dateController.addListener(() => _clearError("date")); _timeController.addListener(() => _clearError("time")); } @override void dispose() { _trainNoFocusNode.dispose(); _trainNoController.dispose(); _hotelNameController.dispose(); _fromController.dispose(); _toController.dispose(); _dateController.dispose(); _timeController.dispose(); _trainCommentsController.dispose(); super.dispose(); } void _clearError(String field) { if (mounted && errorMessages.containsKey(field)) { setState(() { errorMessages.remove(field); }); } } bool isValidData(Map data) { errorMessages.clear(); // Reset errors // Required fields that must not be empty List requiredFields = ["train_no", "class","from_station", "to_station","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 $trainData"); Map data = trainData; if (!isValidData(data)) { print("Validation Failed: Required fields are missing."); setState(() {}); return; // Stop execution if validation fails }else { widget.onSavetrain(trainData); } 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: [ Align( alignment: Alignment.centerRight, child: InkWell( onTap: () { widget.onClose(false); }, child: Icon( Icons.close, size: 18, color: Color(0xFF575A74), ), ), ), Text("Train Booking List", style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold,color: Color(0xFF575A74))), SizedBox( height: 6, ), Padding( padding: const EdgeInsets.all(28.0), child: Center( child: Column(children: _buildAccomadtionForm(isDesktop)), ), ) ], ), ), ), ); }); } List _buildAccomadtionForm (bool isDesktop) { List buildResponsiveRow(List children) { return [ isDesktop ? Row(children: children) : Column(children: children), SizedBox(height: 10), ]; } List> 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 Row( mainAxisAlignment: MainAxisAlignment.end, children: _handleAction(isDesktop), ), ]; } List _buildFirstRow(isDesktop) { return [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Train Number", style: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xFF575A74)), ), SizedBox(height: 5), isDesktop ? Row(children: _buildTripType(isDesktop) ) : Column( children: _buildTripType(isDesktop) ), if (errorMessages["train_no"] != null) ...[ SizedBox(height: 5), // Space before error message Text( "Required", style: TextStyle(color: Colors.red, fontSize: 12), ), ], ], ), if (isDesktop) Spacer() else SizedBox( height: 8, ), ]; } List _buildTripType(bool isDesktop){ List purposeList = widget.apiData?['flight_trip_type'] ?? []; List> dropdownItems = purposeList .map((item)=>DropdownMenuItem( value: item['dropdown_value'], child: Text(item['dropdown_value']), )).toList(); if (dropdownItems.isEmpty) { dropdownItems.add( DropdownMenuItem( 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: _trainNoFocused, isDesktop: isDesktop, child: SizedBox( height: 40, child: TextField( focusNode: _trainNoFocusNode, controller: _trainNoController, style: TextStyle(fontSize: 12), decoration: InputDecoration( labelText: "Train number", labelStyle: TextStyle(fontSize: 12, color: Colors.grey), floatingLabelBehavior: FloatingLabelBehavior.never, border: InputBorder.none, contentPadding: EdgeInsets.symmetric(vertical: 16), ), ), ), ), ]; } List _builClassType(bool isDesktop){ List purposeList = widget.apiData?['train_class'] ?? []; List> dropdownItems = purposeList .map((item)=>DropdownMenuItem( value: item['dropdown_key'], child: Text(item['dropdown_value']), )).toList(); if (dropdownItems.isEmpty) { dropdownItems.add( DropdownMenuItem( value: null, child: Text("No options available", style: TextStyle(color: Colors.grey)), ), ); } // Default selected value selectedClass ??= dropdownItems.isNotEmpty ? dropdownItems.first.value : null; return [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Class *", style: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xFF575A74)), ), SizedBox(height: 5), CustomTextFieldWrapper( isFocused: _isHotelNameFocused, isDesktop: isDesktop, child: SizedBox( height: 40, child: DropdownButtonFormField( focusNode: _hotelNameFocusNode, // Assign the correct focus node // controller: _hotelNameController, value: selectedClass, style: TextStyle(fontSize: 12), decoration: InputDecoration( border: InputBorder.none, contentPadding: EdgeInsets.symmetric( horizontal: 10), // Proper padding ), onChanged: purposeList.isNotEmpty ? (newValue) { setState(() { selectedClass = newValue; }); } : null, items: dropdownItems, ), ), ), if (errorMessages["class"] != null) ...[ SizedBox(height: 5), // Space before error message Text( "Required", style: TextStyle(color: Colors.red, fontSize: 12), ), ], ], ), ]; } List _buildSecondRow(bool isDesktop) { DateTime? _selectedCheckOutDate; TimeOfDay? _selectedCheckOutTime; Future _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), ); if (pickedDate != null && pickedDate != _selectedCheckOutDate) { setState(() { _selectedCheckOutDate = pickedDate; _dateController.text = DateFormat('yyyy-MM-dd').format(pickedDate); }); } } Future _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( "From", style: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, 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), 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_station"] != 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: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xFF575A74)), ), SizedBox(height: 5), CustomTextFieldItnerarySubWrapper( isFocused: _toFocus, isDesktop: isDesktop, child: SizedBox( height: 40, child: TextField( focusNode: _toFocusNode, controller: _toController, 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_station"] != 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: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xFF575A74)), ), SizedBox(height: 5), CustomTextFieldItnerarySubWrapper( isFocused: _dateFocus, isDesktop: isDesktop, child: SizedBox( height: 40, child: GestureDetector( onTap: () => _selectCheckOutDate(context), child: AbsorbPointer( child: TextField( focusNode: _dateFocusNode, controller: _dateController, 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: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xFF575A74)), ), SizedBox(height: 5), CustomTextFieldItnerarySubWrapper( isFocused: _timeFocus, isDesktop: isDesktop, child: SizedBox( height: 40, child: GestureDetector( onTap: () => _selectCheckOutTime(context), child: AbsorbPointer( child: TextField( focusNode: _timeFocusNode, controller: _timeController, 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), ), ], ], ), ]; } List _buildThirdRow(bool isDesktop) { return [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Comments", style: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xFF575A74)), ), SizedBox(height: 5), CustomTextFieldWrapper( isFocused: _commentsFocus, // Dropdown doesn't use focus isDesktop: isDesktop, width: isDesktop ? MediaQuery.of(context).size.width * 0.4 : MediaQuery.of(context).size.width * 0.66, child: TextField( focusNode: _commentsFocusNode, controller: _trainCommentsController, maxLines: 6, keyboardType: TextInputType.multiline, 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: 4), ), ), ), ], ) ]; } List _handleAction(bool isDesktop) { return [ // Close Button ElevatedButton( onPressed: () { widget.onClose(false); }, 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: TextStyle(color: Colors.white, fontSize: 14), ), ), SizedBox(width: 10), // Space between buttons // Save Changes Button ElevatedButton( onPressed: () { handleSave(); }, style: ElevatedButton.styleFrom( backgroundColor: Colors.blue, // Primary color for save shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12), ), child: Text( "Save Changes", style: TextStyle(color: Colors.white, fontSize: 14), ), ), ]; } }