// lib/screens/marine/manual/reports/marine_manual_equipment_maintenance_screen.dart

import 'dart:async';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../../../../../auth_provider.dart';
import '../../../../models/marine_manual_equipment_maintenance_data.dart';
import '../../../../services/marine_manual_equipment_maintenance_service.dart';

class MarineManualEquipmentMaintenanceScreen extends StatefulWidget {
  const MarineManualEquipmentMaintenanceScreen({super.key});

  @override
  State<MarineManualEquipmentMaintenanceScreen> createState() =>
      _MarineManualEquipmentMaintenanceScreenState();
}

class _MarineManualEquipmentMaintenanceScreenState
    extends State<MarineManualEquipmentMaintenanceScreen> {
  final _formKey = GlobalKey<FormState>();
  final _data = MarineManualEquipmentMaintenanceData();
  bool _isLoading = false;

  bool _isOnline = true;
  late StreamSubscription<List<ConnectivityResult>> _connectivitySubscription;

  // --- Controllers ---
  final _maintenanceDateController = TextEditingController();
  final _lastMaintenanceDateController = TextEditingController();
  final _timeStartController = TextEditingController();
  final _timeEndController = TextEditingController();

  // YSI controllers
  final _ysiSondeCommentsController = TextEditingController();
  final _ysiSensorCommentsController = TextEditingController();

  // Van Dorn controllers
  final _vanDornCommentsController = TextEditingController();
  final _vanDornCurrentSerialController = TextEditingController();
  final _vanDornNewSerialController = TextEditingController();

  // Controllers for the dynamic tables
  final Map<String, TextEditingController> _ysiCurrentSerialControllers = {};
  final Map<String, TextEditingController> _ysiNewSerialControllers = {};
  final Map<String, TextEditingController> _vanDornLastDateControllers = {};
  final Map<String, TextEditingController> _vanDornNewDateControllers = {};

  // --- MODIFICATION: FocusNodes for validation ---
  final _maintenanceDateFocus = FocusNode();
  final _lastMaintenanceDateFocus = FocusNode();
  final _scheduleMaintenanceFocus = FocusNode();
  final _locationFocus = FocusNode();
  final _timeEndFocus = FocusNode();

  // --- State for Previous Record feature ---
  bool _showPreviousRecordDropdown = false;
  bool _isFetchingPreviousRecords = false;
  List<Map<String, dynamic>> _previousRecords = [];
  int? _selectedPreviousRecordId; // Use ID to track selected record
  // --- End State ---

  // List of scopes for the YSI Sonde section (Section I)
  final List<String> _ysiSondeScopes = [
    '1) Upper body of instrument',
    '2) Side body of instrument',
    '3) Bottom body of instrument',
    '4) Sonde guard and calibration cup',
  ];

  // Map to hold the scope text for YSI sensors (Section II)
  final Map<String, String> _ysiSensorScopes = {
    'pH': '1) Sensor body',
    'Conductivity': '2) Lenses',
    'Turbidity': '3) Pin connector',
    'Dissolved Oxygen': '4) Retaining Nut Kit',
  };

  @override
  void initState() {
    super.initState();
    _maintenanceDateController.text =
        DateFormat('yyyy-MM-dd').format(DateTime.now());

    // Set defaults for Schedule Maintenance and Time Start
    _data.scheduleMaintenance = 'Yes';
    _timeStartController.text = DateFormat('HH:mm').format(DateTime.now()); // Default Time Start

    // --- Init Dynamic Controllers ---
    _data.ysiReplacements.forEach((item, values) {
      _ysiCurrentSerialControllers[item] = TextEditingController();
      _ysiNewSerialControllers[item] = TextEditingController();
    });
    _data.vanDornReplacements.forEach((part, values) {
      _vanDornLastDateControllers[part] = TextEditingController();
      _vanDornNewDateControllers[part] = TextEditingController();
    });

    // --- Connectivity ---
    _checkInitialConnectivity();
    _connectivitySubscription =
        Connectivity().onConnectivityChanged.listen(_updateConnectionStatus);
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    _maintenanceDateController.dispose();
    _lastMaintenanceDateController.dispose();
    _timeStartController.dispose();
    _timeEndController.dispose();
    _ysiSondeCommentsController.dispose();
    _ysiSensorCommentsController.dispose();
    _vanDornCommentsController.dispose();
    _vanDornCurrentSerialController.dispose();
    _vanDornNewSerialController.dispose();

    _ysiCurrentSerialControllers.values.forEach((c) => c.dispose());
    _ysiNewSerialControllers.values.forEach((c) => c.dispose());
    _vanDornLastDateControllers.values.forEach((c) => c.dispose());
    _vanDornNewDateControllers.values.forEach((c) => c.dispose());

    // --- MODIFICATION: Dispose FocusNodes ---
    _maintenanceDateFocus.dispose();
    _lastMaintenanceDateFocus.dispose();
    _scheduleMaintenanceFocus.dispose();
    _locationFocus.dispose();
    _timeEndFocus.dispose();

    super.dispose();
  }

  Future<void> _checkInitialConnectivity() async {
    final connectivityResult = await Connectivity().checkConnectivity();
    _updateConnectionStatus(connectivityResult);
  }

  void _updateConnectionStatus(List<ConnectivityResult> result) {
    final bool currentlyOnline = !result.contains(ConnectivityResult.none);
    if (_isOnline != currentlyOnline) {
      setState(() {
        _isOnline = currentlyOnline;
      });
      if (currentlyOnline && mounted) {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content: Text("You are back online."),
          backgroundColor: Colors.green,
        ));
      }
    }
  }

  Future<void> _selectDate(TextEditingController controller) async {
    final date = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2000),
        lastDate: DateTime(2101));
    if (date != null) {
      controller.text = DateFormat('yyyy-MM-dd').format(date);
    }
  }

  Future<void> _selectTime(TextEditingController controller) async {
    final time = await showTimePicker(
        context: context, initialTime: TimeOfDay.now());
    if (time != null && mounted) {
      controller.text = time.format(context);
    }
  }

  // --- Previous Record Logic ---

  Future<void> _fetchPreviousRecords() async {
    if (_previousRecords.isNotEmpty) return; // Already fetched

    setState(() => _isFetchingPreviousRecords = true);

    try {
      final auth = Provider.of<AuthProvider>(context, listen: false);
      final service =
      Provider.of<MarineManualEquipmentMaintenanceService>(context, listen: false);

      final result = await service.getPreviousMaintenanceLogs(authProvider: auth);

      if (mounted) {
        if (result['success'] == true && result['data'] != null) {
          setState(() {
            _previousRecords = List<Map<String, dynamic>>.from(result['data']);
          });
        } else {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
            content: Text(result['message'] ?? 'Failed to fetch previous records.'),
            backgroundColor: Colors.red,
          ));
          // If fetching fails, reset the dropdown
          setState(() => _showPreviousRecordDropdown = false);
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text("An error occurred fetching records: $e"),
          backgroundColor: Colors.red,
        ));
        setState(() => _showPreviousRecordDropdown = false);
      }
    } finally {
      if (mounted) {
        setState(() => _isFetchingPreviousRecords = false);
      }
    }
  }

  void _populateFormWithRecord(Map<String, dynamic> record) {
    // 1. Last Maintenance Date
    // The previous record's 'maintenance_date' becomes the new 'last_maintenance_date'
    _lastMaintenanceDateController.text = record['maintenance_date'] ?? '';

    // 2. YSI Serial Numbers
    if (record['ysi_replacements'] is List) {
      final List<dynamic> ysiReplacements = record['ysi_replacements'];
      for (var item in ysiReplacements) {
        if (item is Map) {
          final String itemName = item['item_name'] ?? '';
          final String currentSerial = item['current_serial'] ?? '';
          final String newSerial = item['new_serial'] ?? '';

          // Use new_serial if available, otherwise fall back to current_serial
          final serialToUse = (newSerial.isNotEmpty) ? newSerial : currentSerial;

          if (_ysiCurrentSerialControllers.containsKey(itemName)) {
            _ysiCurrentSerialControllers[itemName]!.text = serialToUse;
          }
        }
      }
    }

    // 3. Van Dorn Serial Number
    final String vdCurrentSerial = record['van_dorn_current_serial'] ?? '';
    final String vdNewSerial = record['van_dorn_new_serial'] ?? '';
    _vanDornCurrentSerialController.text = (vdNewSerial.isNotEmpty) ? vdNewSerial : vdCurrentSerial;

    // 4. Van Dorn Replacement Dates
    if (record['van_dorn_replacements'] is List) {
      final List<dynamic> vanDornReplacements = record['van_dorn_replacements'];
      for (var part in vanDornReplacements) {
        if (part is Map) {
          final String partName = part['part_name'] ?? '';
          final String lastDate = part['last_replacement_date'] ?? '';
          final String newDate = part['new_replacement_date'] ?? '';

          // Use new_date if available, otherwise fall back to last_date
          final dateToUse = (newDate.isNotEmpty) ? newDate : lastDate;

          if (_vanDornLastDateControllers.containsKey(partName)) {
            _vanDornLastDateControllers[partName]!.text = dateToUse;
          }
        }
      }
    }

    // Update the UI
    setState(() {});
  }

  void _clearPopulatedData() {
    setState(() {
      _lastMaintenanceDateController.text = '';
      _ysiCurrentSerialControllers.values.forEach((c) => c.text = '');
      _vanDornCurrentSerialController.text = '';
      _vanDornLastDateControllers.values.forEach((c) => c.text = '');
      _selectedPreviousRecordId = null;
    });
  }

  // --- End Previous Record Logic ---

  // --- MODIFICATION: Helper for validation dialog ---
  Future<void> _showErrorDialog(String fieldName, FocusNode focusNode) async {
    await showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Missing Information'),
        content: Text('The "$fieldName" field is required. Please fill it in.'),
        actions: [
          TextButton(
            child: const Text('OK'),
            onPressed: () {
              Navigator.of(ctx).pop(); // Close the dialog
              // Request focus to navigate user to the field
              focusNode.requestFocus();
            },
          ),
        ],
      ),
    );
  }

  Future<void> _submit() async {
    // --- MODIFICATION: Updated validation logic ---

    // 1. Save all fields (especially Dropdowns) to update their values
    _formKey.currentState!.save();

    // 2. Run validation. This highlights all invalid fields.
    if (!_formKey.currentState!.validate()) {
      // 3. Find the *first* invalid field in order and show the error dialog.
      //    This provides a guided user experience.
      if (_maintenanceDateController.text.isEmpty) {
        await _showErrorDialog('Maintenance Date', _maintenanceDateFocus);
      } else if (_lastMaintenanceDateController.text.isEmpty) {
        await _showErrorDialog('Last Maintenance Date', _lastMaintenanceDateFocus);
      } else if (_data.scheduleMaintenance == null) {
        await _showErrorDialog('Schedule Maintenance', _scheduleMaintenanceFocus);
      } else if (_data.location == null || _data.location!.isEmpty) {
        await _showErrorDialog('Location', _locationFocus);
      } else if (_timeEndController.text.isEmpty) {
        await _showErrorDialog('Time End', _timeEndFocus);
      }
      // If validation fails for some other reason, the fields will
      // just be highlighted red, which is standard behavior.
      return;
    }
    // --- END MODIFICATION ---

    // Form validation passed
    setState(() => _isLoading = true);

    try {
      final auth = Provider.of<AuthProvider>(context, listen: false);
      final service =
      Provider.of<MarineManualEquipmentMaintenanceService>(context, listen: false);

      _data.conductedByUserId = auth.profileData?['user_id'];
      _data.maintenanceDate = _maintenanceDateController.text;
      _data.lastMaintenanceDate = _lastMaintenanceDateController.text;
      // scheduleMaintenance & location are set via Dropdown onSaved

      // Assign header fields
      _data.timeStart = _timeStartController.text;
      _data.timeEnd = _timeEndController.text;

      // Assign comments and serials
      _data.ysiSondeComments = _ysiSondeCommentsController.text;
      _data.ysiSensorComments = _ysiSensorCommentsController.text;
      _data.vanDornComments = _vanDornCommentsController.text;
      _data.vanDornCurrentSerial = _vanDornCurrentSerialController.text;
      _data.vanDornNewSerial = _vanDornNewSerialController.text;

      // Assign dynamic table values from their controllers
      _data.ysiReplacements.forEach((item, values) {
        values['Current Serial'] = _ysiCurrentSerialControllers[item]?.text ?? '';
        values['New Serial'] = _ysiNewSerialControllers[item]?.text ?? '';
      });
      _data.vanDornReplacements.forEach((part, values) {
        values['Last Date'] = _vanDornLastDateControllers[part]?.text ?? '';
        values['New Date'] = _vanDornNewDateControllers[part]?.text ?? '';
      });

      // Submit the data
      final result =
      await service.submitMaintenanceReport(data: _data, authProvider: auth);

      // Handle the result
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text(result['message']),
          backgroundColor: result['success'] == true ? Colors.green : Colors.red,
        ));
        if (result['success'] == true) Navigator.of(context).pop();
      }
    } on SocketException {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content:
          Text("Submission failed. Please check your network connection."),
          backgroundColor: Colors.red,
        ));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text("An unexpected error occurred: $e"),
          backgroundColor: Colors.red,
        ));
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Equipment Maintenance (F-MM01)'),
      ),
      body: Column(
        children: [
          if (!_isOnline)
            Container(
              width: double.infinity,
              color: Colors.red,
              padding: const EdgeInsets.all(8.0),
              child: const Text(
                'No Internet Connection. You cannot submit the report.',
                style: const TextStyle(color: Colors.white),
                textAlign: TextAlign.center,
              ),
            ),
          Expanded(
            child: Form(
              key: _formKey,
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    _buildHeaderCard(),
                    const SizedBox(height: 16),
                    _buildPart1YsiCard(),
                    const SizedBox(height: 16),
                    _buildPart1YsiReplacementCard(),
                    const SizedBox(height: 16),
                    _buildPart2VanDornCard(),
                    const SizedBox(height: 16),
                    _buildPart2VanDornReplacementCard(),
                    const SizedBox(height: 24),
                    Row(
                      children: [
                        Expanded(
                            child: OutlinedButton(
                                onPressed: _isLoading ? null : () => Navigator.of(context).pop(), // Disable cancel during loading
                                child: const Text('Cancel'))),
                        const SizedBox(width: 10.0),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _isLoading || !_isOnline ? null : _submit,
                            child: _isLoading
                                ? const SizedBox( // Use SizedBox for consistent button height
                              height: 20,
                              width: 20,
                              child: CircularProgressIndicator(
                                strokeWidth: 2.0,
                                color: Colors.white,
                              ),
                            )
                                : const Text('Submit'),
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // --- Card Widgets ---

  Widget _buildHeaderCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Header Information', style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 16),
            // --- NEW FIELD: Use Previous Record ---
            DropdownButtonFormField<String>(
              decoration: const InputDecoration(
                labelText: 'Use previous record data',
                border: OutlineInputBorder(),
              ),
              value: _showPreviousRecordDropdown ? 'Yes' : 'No',
              items: ['Yes', 'No'].map((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
              onChanged: _isLoading || !_isOnline ? null : (val) { // Disable if loading or offline
                setState(() {
                  if (val == 'Yes') {
                    _showPreviousRecordDropdown = true;
                    _fetchPreviousRecords(); // Fetch data when user selects Yes
                  } else {
                    _showPreviousRecordDropdown = false;
                    _clearPopulatedData(); // Clear fields if user selects No
                  }
                });
              },
            ),
            // --- NEW FIELD: Previous Record Dropdown ---
            if (_showPreviousRecordDropdown)
              Padding(
                padding: const EdgeInsets.only(top: 16.0),
                child: _isFetchingPreviousRecords
                    ? const Center(child: CircularProgressIndicator())
                    : DropdownButtonFormField<int>(
                  decoration: const InputDecoration(
                    labelText: 'Select previous record (last 4 months)', // Updated label
                    border: OutlineInputBorder(),
                  ),
                  value: _selectedPreviousRecordId,
                  isExpanded: true, // Allow text to wrap if needed
                  hint: Text(_previousRecords.isEmpty
                      ? 'No records found'
                      : 'Select a record'),
                  disabledHint: const Text('Fetching records...'),
                  items: _previousRecords.map((record) {
                    // --- MODIFIED: Display Date and Name ---
                    String conductedByName = record['conducted_by_name'] ?? 'Unknown User';
                    String maintenanceDate = record['maintenance_date'] ?? 'Unknown Date';
                    String displayText = '$maintenanceDate (by $conductedByName)';
                    // --- END MODIFICATION ---
                    return DropdownMenuItem<int>(
                      value: record['maintenance_id'] as int, // Assuming API returns 'maintenance_id'
                      // Use FittedBox to prevent overflow, consider TextOverflow.ellipsis too
                      child: FittedBox(
                        fit: BoxFit.scaleDown,
                        child: Text(displayText),
                      ),
                    );
                  }).toList(),
                  onChanged: _isLoading || _previousRecords.isEmpty ? null : (val) { // Disable if loading or no records
                    if (val == null) return;
                    // Find the full record map and populate form
                    final selectedRecord = _previousRecords
                        .firstWhere((r) => r['maintenance_id'] == val);
                    setState(() {
                      _selectedPreviousRecordId = val;
                      _populateFormWithRecord(selectedRecord);
                    });
                  },
                ),
              ),
            const SizedBox(height: 16),
            // --- END NEW FIELDS ---
            TextFormField(
              controller: _maintenanceDateController,
              focusNode: _maintenanceDateFocus, // <-- MODIFICATION
              readOnly: true,
              decoration: const InputDecoration(
                  labelText: 'Maintenance Date *',
                  border: OutlineInputBorder(),
                  suffixIcon: Icon(Icons.calendar_month)),
              onTap: _isLoading ? null : () => _selectDate(_maintenanceDateController), // Disable tap when loading
              validator: (val) => val == null || val.isEmpty ? 'Date is required' : null,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _lastMaintenanceDateController,
              focusNode: _lastMaintenanceDateFocus, // <-- MODIFICATION
              readOnly: true,
              decoration: const InputDecoration(
                  labelText: 'Last Maintenance Date *', // <-- MODIFICATION
                  border: OutlineInputBorder(),
                  suffixIcon: Icon(Icons.calendar_month)),
              onTap: _isLoading ? null : () => _selectDate(_lastMaintenanceDateController), // Disable tap when loading
              validator: (val) => val == null || val.isEmpty ? 'Date is required' : null, // <-- MODIFICATION
            ),
            const SizedBox(height: 16),
            // Changed to DropdownButtonFormField
            DropdownButtonFormField<String>(
              focusNode: _scheduleMaintenanceFocus, // <-- MODIFICATION
              decoration: const InputDecoration(
                labelText: 'Schedule Maintenance *',
                border: OutlineInputBorder(),
              ),
              value: _data.scheduleMaintenance, // Set from initState
              items: ['Yes', 'No'].map((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
              onChanged: _isLoading ? null : (val) {
                setState(() {
                  _data.scheduleMaintenance = val; // Update data on change
                });
              },
              onSaved: (val) {
                _data.scheduleMaintenance = val; // Save data on form save
              },
              validator: (val) => val == null ? 'Please select an option' : null,
            ),
            const SizedBox(height: 16),
            DropdownButtonFormField<String>(
              focusNode: _locationFocus, // <-- MODIFICATION
              decoration: const InputDecoration(
                labelText: 'Location *',
                border: OutlineInputBorder(),
              ),
              value: _data.location, // Use the value from the data model
              items: ['HQ', 'Regional'].map((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
              onChanged: _isLoading ? null : (val) {
                setState(() {
                  _data.location = val; // Update data on change
                });
              },
              onSaved: (val) {
                _data.location = val; // Save data on form save
              },
              validator: (val) => val == null || val.isEmpty ? 'Location is required' : null,
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _timeStartController,
                    readOnly: true, // Always read-only as it's defaulted
                    decoration: const InputDecoration(
                        labelText: 'Time Start',
                        border: OutlineInputBorder(),
                        suffixIcon: Icon(Icons.access_time)),
                    // onTap removed
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: TextFormField(
                    controller: _timeEndController,
                    focusNode: _timeEndFocus, // <-- MODIFICATION
                    readOnly: true, // Make readOnly to prevent manual edit after selection
                    decoration: const InputDecoration(
                        labelText: 'Time End *',
                        border: OutlineInputBorder(),
                        suffixIcon: Icon(Icons.access_time)),
                    onTap: _isLoading ? null : () => _selectTime(_timeEndController), // Disable tap when loading
                    validator: (val) => val == null || val.isEmpty ? 'Time End is required' : null,
                  ),
                ),
              ],
            ),
            // END MOVED FIELDS
            const SizedBox(height: 8),
            CheckboxListTile(
              title: const Text('Sonde / Sensor/Tip/Part Replacement'),
              value: _data.isReplacement,
              onChanged: _isLoading ? null : (val) { // Disable when loading
                setState(() => _data.isReplacement = val ?? false);
              },
              controlAffinity: ListTileControlAffinity.leading,
              contentPadding: EdgeInsets.zero,
            )
          ],
        ),
      ),
    );
  }

  Widget _buildPart1YsiCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: AbsorbPointer( // Disable interaction when loading
          absorbing: _isLoading,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Part 1 - YSI EXO 2 & Sensor', style: Theme.of(context).textTheme.titleLarge),
              // Location and Time fields removed from here
              const Divider(height: 24),
              // Use the correct widget for Section I (Sonde)
              _buildSondeChecklistSection(
                  'I. YSI EXO 2 Multiparameter Sonde', _ysiSondeScopes),
              TextFormField(
                controller: _ysiSondeCommentsController,
                decoration: const InputDecoration(
                    labelText: 'Comment/Observation',
                    border: OutlineInputBorder(),
                    alignLabelWithHint: true),
                maxLines: 3,
                readOnly: _isLoading,
                onSaved: (val) => _data.ysiSondeComments = val,
              ),
              const Divider(height: 24),
              // Use the correct widget for Section II (Sensor)
              _buildSensorChecklistSection('II. EXO Sensor', _data.ysiSensorChecks),
              TextFormField(
                controller: _ysiSensorCommentsController,
                decoration: const InputDecoration(
                    labelText: 'Comment/Observation',
                    border: OutlineInputBorder(),
                    alignLabelWithHint: true),
                maxLines: 3,
                readOnly: _isLoading,
                onSaved: (val) => _data.ysiSensorComments = val,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPart1YsiReplacementCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: AbsorbPointer( // Disable interaction when loading
          absorbing: _isLoading,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Part 1 - Sonde / Sensor / Tip Replacement',
                  style: Theme.of(context).textTheme.titleLarge),
              const SizedBox(height: 16),
              ..._data.ysiReplacements.keys.map((item) {
                return Padding(
                  padding: const EdgeInsets.only(bottom: 16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(item, style: Theme.of(context).textTheme.titleMedium),
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          Expanded(
                            child: TextFormField(
                              controller: _ysiCurrentSerialControllers[item],
                              decoration: const InputDecoration(
                                  labelText: 'Current Serial Number',
                                  border: OutlineInputBorder()),
                              readOnly: _isLoading,
                              // onSaved handled in _submit
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: TextFormField(
                              controller: _ysiNewSerialControllers[item],
                              decoration: const InputDecoration(
                                  labelText: 'New Serial Number',
                                  border: OutlineInputBorder()),
                              readOnly: _isLoading,
                              // onSaved handled in _submit
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                );
              }).toList(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPart2VanDornCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: AbsorbPointer( // Disable interaction when loading
          absorbing: _isLoading,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Part 2 - Van Dorn Sampler', style: Theme.of(context).textTheme.titleLarge),
              const SizedBox(height: 8),
              Text('Schedule Maintenance - Inspection & Cleaning',
                  style: Theme.of(context).textTheme.titleMedium),
              const Divider(height: 24),
              // Use the correct widget for Section III (Van Dorn Checks)
              _buildChecklistSection(
                  'III. Van Dorn Sampler', _data.vanDornChecks),
              TextFormField(
                controller: _vanDornCommentsController,
                decoration: const InputDecoration(
                    labelText: 'Comment/Observation',
                    border: OutlineInputBorder(),
                    alignLabelWithHint: true),
                maxLines: 3,
                readOnly: _isLoading,
                onSaved: (val) => _data.vanDornComments = val,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPart2VanDornReplacementCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: AbsorbPointer( // Disable interaction when loading
          absorbing: _isLoading,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Part 2 - Van Dorn Sampler Part Replacement',
                  style: Theme.of(context).textTheme.titleLarge),
              const SizedBox(height: 16),
              Row(
                children: [
                  Expanded(
                    child: TextFormField(
                      controller: _vanDornCurrentSerialController,
                      decoration: const InputDecoration(
                          labelText: 'Current Serial Number',
                          border: OutlineInputBorder()),
                      readOnly: _isLoading,
                      // onSaved handled in _submit
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: TextFormField(
                      controller: _vanDornNewSerialController,
                      decoration: const InputDecoration(
                          labelText: 'New Serial Number',
                          border: OutlineInputBorder()),
                      readOnly: _isLoading,
                      // onSaved handled in _submit
                    ),
                  ),
                ],
              ),
              const Divider(height: 24),
              ..._data.vanDornReplacements.keys.map((part) {
                return Padding(
                  padding: const EdgeInsets.only(bottom: 16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(part, style: Theme.of(context).textTheme.titleMedium),
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          Expanded(
                            child: TextFormField(
                              controller: _vanDornLastDateControllers[part],
                              readOnly: true, // Always readOnly, selected via picker
                              decoration: const InputDecoration(
                                  labelText: 'Last Replacement Date',
                                  border: OutlineInputBorder(),
                                  suffixIcon: Icon(Icons.calendar_month)),
                              onTap: _isLoading ? null : () => _selectDate(_vanDornLastDateControllers[part]!), // Disable tap
                              // onSaved handled in _submit
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: TextFormField(
                              controller: _vanDornNewDateControllers[part],
                              readOnly: true, // Always readOnly, selected via picker
                              decoration: const InputDecoration(
                                  labelText: 'New Replacement Date',
                                  border: OutlineInputBorder(),
                                  suffixIcon: Icon(Icons.calendar_month)),
                              onTap: _isLoading ? null : () => _selectDate(_vanDornNewDateControllers[part]!), // Disable tap
                              // onSaved handled in _submit
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                );
              }).toList(),
            ],
          ),
        ),
      ),
    );
  }

  // --- Helper Widgets ---

  // Widget for Section I (YSI Sonde) - Uses List<String> for scopes
  Widget _buildSondeChecklistSection(String title, List<String> scopes) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title, style: Theme.of(context).textTheme.titleMedium),
        const SizedBox(height: 8),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: scopes.map((scope) => Padding(
              padding: const EdgeInsets.only(bottom: 4.0),
              child: Text(scope, style: Theme.of(context).textTheme.bodyLarge),
            )).toList(),
          ),
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(
              child: CheckboxListTile(
                title: const Text('Inspect'),
                value: _data.ysiSondeChecks['Inspect'],
                onChanged: _isLoading ? null : (val) { // Disable when loading
                  setState(() => _data.ysiSondeChecks['Inspect'] = val ?? false);
                },
                controlAffinity: ListTileControlAffinity.leading,
                contentPadding: EdgeInsets.zero,
              ),
            ),
            Expanded(
              child: CheckboxListTile(
                title: const Text('Clean'),
                value: _data.ysiSondeChecks['Clean'],
                onChanged: _isLoading ? null : (val) { // Disable when loading
                  setState(() => _data.ysiSondeChecks['Clean'] = val ?? false);
                },
                controlAffinity: ListTileControlAffinity.leading,
                contentPadding: EdgeInsets.zero,
              ),
            ),
          ],
        ),
      ],
    );
  }

  // Helper widget for the Sensor checklist (Part 1, Section II) - Uses Map for items
  Widget _buildSensorChecklistSection(
      String title, Map<String, Map<String, bool>> items) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title, style: Theme.of(context).textTheme.titleMedium),
        const SizedBox(height: 8),
        Table(
          columnWidths: const {
            0: FlexColumnWidth(2), // Sensor
            1: FlexColumnWidth(3), // Scope
            2: FlexColumnWidth(1), // Inspect
            3: FlexColumnWidth(1), // Clean
          },
          border: TableBorder.all(color: Colors.grey.shade400),
          children: [
            TableRow(
              decoration: BoxDecoration(color: Colors.grey.shade600),
              children: [
                _tableHeader('Sensor'),
                _tableHeader('Scope'),
                _tableHeader('Inspect'),
                _tableHeader('Clean'),
              ],
            ),
            ..._ysiSensorScopes.keys.map((sensorName) {
              final scopeText = _ysiSensorScopes[sensorName]!;
              final itemChecks = items[sensorName]!; // Use sensorName as key
              return TableRow(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(sensorName),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(scopeText),
                  ),
                  Checkbox(
                    value: itemChecks['Inspect'],
                    onChanged: _isLoading ? null : (val) { // Disable when loading
                      setState(() => itemChecks['Inspect'] = val ?? false);
                    },
                    activeColor: Theme.of(context).colorScheme.primary,
                  ),
                  Checkbox(
                    value: itemChecks['Clean'],
                    onChanged: _isLoading ? null : (val) { // Disable when loading
                      setState(() => itemChecks['Clean'] = val ?? false);
                    },
                    activeColor: Theme.of(context).colorScheme.primary,
                  ),
                ],
              );
            }).toList(),
          ],
        ),
        const SizedBox(height: 16),
      ],
    );
  }

  // Helper widget for Van Dorn checklist (Part 2, Section III) - Uses Map for items
  Widget _buildChecklistSection(
      String title, Map<String, Map<String, bool>> items) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title, style: Theme.of(context).textTheme.titleMedium),
        const SizedBox(height: 8),
        Table(
          columnWidths: const {
            0: FlexColumnWidth(3),
            1: FlexColumnWidth(1),
            2: FlexColumnWidth(1),
          },
          border: TableBorder.all(color: Colors.grey.shade400),
          children: [
            TableRow(
              decoration: BoxDecoration(color: Colors.grey.shade600),
              children: [
                _tableHeader('Scope'),
                _tableHeader('Inspect'),
                _tableHeader('Clean'),
              ],
            ),
            ...items.keys.map((scope) {
              return TableRow(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(scope),
                  ),
                  Checkbox(
                    value: items[scope]!['Inspect'],
                    onChanged: _isLoading ? null : (val) { // Disable when loading
                      setState(() => items[scope]!['Inspect'] = val ?? false);
                    },
                    activeColor: Theme.of(context).colorScheme.primary,
                  ),
                  // Conditionally render the "Clean" checkbox
                  items[scope]!.containsKey('Clean')
                      ? Checkbox(
                    value: items[scope]!['Clean'],
                    onChanged: _isLoading ? null : (val) { // Disable when loading
                      setState(() => items[scope]!['Clean'] = val ?? false);
                    },
                    activeColor: Theme.of(context).colorScheme.primary,
                  )
                      : Container(), // Render empty if 'Clean' is not applicable
                ],
              );
            }).toList(),
          ],
        ),
        const SizedBox(height: 16),
      ],
    );
  }

  Widget _tableHeader(String text) {
    // Use contrasting color for header text if needed, else rely on theme
    final headerColor = Colors.grey.shade600; // Match TableRow background
    final textColor = headerColor.computeLuminance() > 0.5 ? Colors.black87 : Colors.white;
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(text, style: TextStyle(fontWeight: FontWeight.bold, color: textColor)),
    );
  }
} // End of State class