// lib/screens/river/manual/widgets/river_in_situ_step_3_data_capture.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:usb_serial/usb_serial.dart';
import 'package:intl/intl.dart';

import '../../../../models/river_in_situ_sampling_data.dart';
import '../../../../services/river_in_situ_sampling_service.dart';
import '../../../../bluetooth/bluetooth_manager.dart';
import '../../../../serial/serial_manager.dart';
import '../../../../bluetooth/widgets/bluetooth_device_list_dialog.dart';
import '../../../../serial/widget/serial_port_list_dialog.dart';

class RiverInSituStep3DataCapture extends StatefulWidget {
  final RiverInSituSamplingData data;
  final VoidCallback onNext;

  const RiverInSituStep3DataCapture({
    super.key,
    required this.data,
    required this.onNext,
  });

  @override
  State<RiverInSituStep3DataCapture> createState() => _RiverInSituStep3DataCaptureState();
}

class _RiverInSituStep3DataCaptureState extends State<RiverInSituStep3DataCapture> {
  final _formKey = GlobalKey<FormState>();
  bool _isLoading = false;
  bool _isAutoReading = false;
  StreamSubscription? _dataSubscription;

  final List<Map<String, dynamic>> _parameters = [];

  // Sonde parameter controllers
  final _sondeIdController = TextEditingController();
  final _dateController = TextEditingController();
  final _timeController = TextEditingController();
  final _oxyConcController = TextEditingController();
  final _oxySatController = TextEditingController();
  final _phController = TextEditingController();
  final _salinityController = TextEditingController();
  final _ecController = TextEditingController();
  final _tempController = TextEditingController();
  final _tdsController = TextEditingController();
  final _turbidityController = TextEditingController();
  final _tssController = TextEditingController();
  final _batteryController = TextEditingController();

  // ADDED: Flowrate controllers and state
  String? _selectedFlowrateMethod;
  final _flowrateValueController = TextEditingController();
  final _sdHeightController = TextEditingController();
  final _sdDistanceController = TextEditingController();
  final _sdTimeFirstController = TextEditingController();
  final _sdTimeLastController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _initializeControllers();
    _initializeFlowrateControllers();
  }

  @override
  void dispose() {
    _dataSubscription?.cancel();
    _disposeControllers();
    _disposeFlowrateControllers();
    super.dispose();
  }

  void _initializeControllers() {
    widget.data.dataCaptureDate = widget.data.samplingDate;
    widget.data.dataCaptureTime = widget.data.samplingTime;

    _sondeIdController.text = widget.data.sondeId ?? '';
    _dateController.text = widget.data.dataCaptureDate ?? '';
    _timeController.text = widget.data.dataCaptureTime ?? '';

    _oxyConcController.text = widget.data.oxygenConcentration?.toString() ?? '-999.0';
    _oxySatController.text = widget.data.oxygenSaturation?.toString() ?? '-999.0';
    _phController.text = widget.data.ph?.toString() ?? '-999.0';
    _salinityController.text = widget.data.salinity?.toString() ?? '-999.0';
    _ecController.text = widget.data.electricalConductivity?.toString() ?? '-999.0';
    _tempController.text = widget.data.temperature?.toString() ?? '-999.0';
    _tdsController.text = widget.data.tds?.toString() ?? '-999.0';
    _turbidityController.text = widget.data.turbidity?.toString() ?? '-999.0';
    _tssController.text = widget.data.tss?.toString() ?? '-999.0';
    _batteryController.text = widget.data.batteryVoltage?.toString() ?? '-999.0';

    if (_parameters.isEmpty) {
      _parameters.addAll([
        {'icon': Icons.air, 'label': 'Oxygen Conc.', 'unit': 'mg/L', 'controller': _oxyConcController},
        {'icon': Icons.percent, 'label': 'Oxygen Sat.', 'unit': '%', 'controller': _oxySatController},
        {'icon': Icons.science_outlined, 'label': 'pH', 'unit': '', 'controller': _phController},
        {'icon': Icons.waves, 'label': 'Salinity', 'unit': 'ppt', 'controller': _salinityController},
        {'icon': Icons.flash_on, 'label': 'Conductivity', 'unit': 'µS/cm', 'controller': _ecController},
        {'icon': Icons.thermostat, 'label': 'Temperature', 'unit': '°C', 'controller': _tempController},
        {'icon': Icons.grain, 'label': 'TDS', 'unit': 'mg/L', 'controller': _tdsController},
        {'icon': Icons.opacity, 'label': 'Turbidity', 'unit': 'NTU', 'controller': _turbidityController},
        {'icon': Icons.filter_alt_outlined, 'label': 'TSS', 'unit': 'mg/L', 'controller': _tssController},
        {'icon': Icons.battery_charging_full, 'label': 'Battery', 'unit': 'V', 'controller': _batteryController},
      ]);
    }
  }

  void _disposeControllers() {
    _sondeIdController.dispose();
    _dateController.dispose();
    _timeController.dispose();
    _oxyConcController.dispose();
    _oxySatController.dispose();
    _phController.dispose();
    _salinityController.dispose();
    _ecController.dispose();
    _tempController.dispose();
    _tdsController.dispose();
    _turbidityController.dispose();
    _tssController.dispose();
    _batteryController.dispose();
  }

  // --- START: Flowrate Logic ---
  void _initializeFlowrateControllers() {
    _selectedFlowrateMethod = widget.data.flowrateMethod;
    _flowrateValueController.text = widget.data.flowrateValue?.toString() ?? '';
    _sdHeightController.text = widget.data.flowrateSurfaceDrifterHeight?.toString() ?? '';
    _sdDistanceController.text = widget.data.flowrateSurfaceDrifterDistance?.toString() ?? '';
    _sdTimeFirstController.text = widget.data.flowrateSurfaceDrifterTimeFirst ?? '';
    _sdTimeLastController.text = widget.data.flowrateSurfaceDrifterTimeLast ?? '';
  }

  void _disposeFlowrateControllers() {
    _flowrateValueController.dispose();
    _sdHeightController.dispose();
    _sdDistanceController.dispose();
    _sdTimeFirstController.dispose();
    _sdTimeLastController.dispose();
  }

  void _onFlowrateMethodChanged(String? value) {
    setState(() {
      _selectedFlowrateMethod = value;
      if (value == 'NA') {
        _flowrateValueController.text = 'NA';
      } else if (value == 'Flowmeter') {
        _flowrateValueController.clear();
      } else {
        // Clear calculated value when switching back to Surface Drifter
        _flowrateValueController.clear();
      }
    });
  }

  void _calculateFlowrate() {
    final distance = double.tryParse(_sdDistanceController.text);
    final timeFirstStr = _sdTimeFirstController.text;
    final timeLastStr = _sdTimeLastController.text;

    if (distance == null || timeFirstStr.isEmpty || timeLastStr.isEmpty) {
      _showSnackBar("Please fill in Distance, Time First, and Time Last.", isError: true);
      return;
    }

    try {
      final timeFormat = DateFormat("HH:mm:ss");
      final timeFirst = timeFormat.parse(timeFirstStr);
      final timeLast = timeFormat.parse(timeLastStr);

      final differenceInSeconds = timeLast.difference(timeFirst).inSeconds;

      if (differenceInSeconds <= 0) {
        _showSnackBar("Time Last Deploy must be after Time First Deploy.", isError: true);
        return;
      }

      final flowrate = distance / differenceInSeconds;
      setState(() {
        _flowrateValueController.text = flowrate.toStringAsFixed(4);
      });
    } catch (e) {
      _showSnackBar("Invalid time format. Please use HH:mm:ss.", isError: true);
    }
  }

  Future<void> _selectTime(BuildContext context, TextEditingController controller) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );
    if (picked != null) {
      final now = DateTime.now();
      final dt = DateTime(now.year, now.month, now.day, picked.hour, picked.minute);
      setState(() {
        controller.text = DateFormat('HH:mm:ss').format(dt);
      });
    }
  }
  // --- END: Flowrate Logic ---


  Future<void> _handleConnectionAttempt(String type) async {
    final service = context.read<RiverInSituSamplingService>();
    final bool hasPermissions = await service.requestDevicePermissions();
    if (!hasPermissions && mounted) {
      _showSnackBar("Bluetooth & Location permissions are required to connect.", isError: true);
      return;
    }
    _disconnectFromAll();
    await Future.delayed(const Duration(milliseconds: 250));
    final bool connectionSuccess = await _connectToDevice(type);
    if (connectionSuccess && mounted) {
      _dataSubscription?.cancel();
      final stream = type == 'bluetooth' ? service.bluetoothDataStream : service.serialDataStream;
      _dataSubscription = stream.listen((readings) {
        if (mounted) {
          _updateTextFields(readings);
        }
      });
    }
  }

  Future<bool> _connectToDevice(String type) async {
    setState(() => _isLoading = true);
    final service = context.read<RiverInSituSamplingService>();
    bool success = false;
    try {
      if (type == 'bluetooth') {
        final devices = await service.getPairedBluetoothDevices();
        if (devices.isEmpty && mounted) {
          _showSnackBar('No paired Bluetooth devices found.', isError: true);
          return false;
        }
        final selectedDevice = await showBluetoothDeviceListDialog(context: context, devices: devices);
        if (selectedDevice != null) {
          await service.connectToBluetoothDevice(selectedDevice);
          success = true;
        }
      } else if (type == 'serial') {
        final devices = await service.getAvailableSerialDevices();
        if (devices.isEmpty && mounted) {
          _showSnackBar('No USB Serial devices found.', isError: true);
          return false;
        }
        final selectedDevice = await showSerialPortListDialog(context: context, devices: devices);
        if (selectedDevice != null) {
          await service.connectToSerialDevice(selectedDevice);
          success = true;
        }
      }
    } catch (e) {
      if (mounted) _showSnackBar('Connection failed: $e', isError: true);
      success = false;
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
    return success;
  }

  void _toggleAutoReading(String activeType) {
    final service = context.read<RiverInSituSamplingService>();
    setState(() {
      _isAutoReading = !_isAutoReading;
      if (_isAutoReading) {
        if (activeType == 'bluetooth') service.startBluetoothAutoReading();
        else service.startSerialAutoReading();
      } else {
        if (activeType == 'bluetooth') service.stopBluetoothAutoReading();
        else service.stopSerialAutoReading();
      }
    });
  }

  void _disconnect(String type) {
    final service = context.read<RiverInSituSamplingService>();
    if (type == 'bluetooth') {
      service.disconnectFromBluetooth();
    } else {
      service.disconnectFromSerial();
    }
    _dataSubscription?.cancel();
    _dataSubscription = null;
    if (mounted) {
      setState(() => _isAutoReading = false);
    }
  }

  void _disconnectFromAll() {
    final service = context.read<RiverInSituSamplingService>();
    if (service.bluetoothConnectionState.value != BluetoothConnectionState.disconnected) {
      _disconnect('bluetooth');
    }
    if (service.serialConnectionState.value != SerialConnectionState.disconnected) {
      _disconnect('serial');
    }
  }

  void _updateTextFields(Map<String, double> readings) {
    const defaultValue = -999.0;
    setState(() {
      _oxyConcController.text = (readings['Optical Dissolved Oxygen: Compensated mg/L'] ?? defaultValue).toStringAsFixed(5);
      _oxySatController.text = (readings['Optical Dissolved Oxygen: Compensated % Saturation'] ?? defaultValue).toStringAsFixed(5);
      _phController.text = (readings['PH: PH units'] ?? defaultValue).toStringAsFixed(5);
      _tempController.text = (readings['External Temp: Degrees Celcius'] ?? defaultValue).toStringAsFixed(5);
      _ecController.text = (readings['Conductivity: us/cm'] ?? defaultValue).toStringAsFixed(5);
      _salinityController.text = (readings['Conductivity: Salinity'] ?? defaultValue).toStringAsFixed(5);
      _tdsController.text = (readings['Conductivity:TDS mg/L'] ?? defaultValue).toStringAsFixed(5);
      _tssController.text = (readings['Turbidity: TSS'] ?? defaultValue).toStringAsFixed(5);
      _turbidityController.text = (readings['Turbidity: FNU'] ?? defaultValue).toStringAsFixed(5);
      _batteryController.text = (readings['Sonde: Battery Voltage'] ?? defaultValue).toStringAsFixed(5);
    });
  }

  void _goToNextStep() {
    if (_isAutoReading) {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
                title: const Text('Data Collection Active'),
                content: const Text('Please stop the live data collection before proceeding.'),
                actions: <Widget>[
                  TextButton(child: const Text('OK'), onPressed: () => Navigator.of(context).pop())
                ]);
          });
      return;
    }

    if (_formKey.currentState!.validate()){
      _formKey.currentState!.save();
      try {
        const defaultValue = -999.0;
        widget.data.temperature = double.tryParse(_tempController.text) ?? defaultValue;
        widget.data.ph = double.tryParse(_phController.text) ?? defaultValue;
        widget.data.salinity = double.tryParse(_salinityController.text) ?? defaultValue;
        widget.data.electricalConductivity = double.tryParse(_ecController.text) ?? defaultValue;
        widget.data.oxygenConcentration = double.tryParse(_oxyConcController.text) ?? defaultValue;
        widget.data.oxygenSaturation = double.tryParse(_oxySatController.text) ?? defaultValue;
        widget.data.tds = double.tryParse(_tdsController.text) ?? defaultValue;
        widget.data.turbidity = double.tryParse(_turbidityController.text) ?? defaultValue;
        widget.data.tss = double.tryParse(_tssController.text) ?? defaultValue;
        widget.data.batteryVoltage = double.tryParse(_batteryController.text) ?? defaultValue;

        // Save flowrate data
        widget.data.flowrateMethod = _selectedFlowrateMethod;
        if (_selectedFlowrateMethod == 'Surface Drifter') {
          widget.data.flowrateSurfaceDrifterHeight = double.tryParse(_sdHeightController.text);
          widget.data.flowrateSurfaceDrifterDistance = double.tryParse(_sdDistanceController.text);
          widget.data.flowrateSurfaceDrifterTimeFirst = _sdTimeFirstController.text;
          widget.data.flowrateSurfaceDrifterTimeLast = _sdTimeLastController.text;
          widget.data.flowrateValue = double.tryParse(_flowrateValueController.text);
        } else if (_selectedFlowrateMethod == 'Flowmeter') {
          widget.data.flowrateValue = double.tryParse(_flowrateValueController.text);
        } else { // NA
          widget.data.flowrateValue = null;
        }

      } catch (e) {
        _showSnackBar("Could not save parameters due to a data format error.", isError: true);
        return;
      }
      widget.onNext();
    }
  }

  void _showSnackBar(String message, {bool isError = false}) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : null,
      ));
    }
  }

  Map<String, dynamic>? _getActiveConnectionDetails() {
    final service = context.watch<RiverInSituSamplingService>();
    if (service.bluetoothConnectionState.value != BluetoothConnectionState.disconnected) {
      return {'type': 'bluetooth', 'state': service.bluetoothConnectionState.value, 'name': service.connectedBluetoothDeviceName};
    }
    if (service.serialConnectionState.value != SerialConnectionState.disconnected) {
      return {'type': 'serial', 'state': service.serialConnectionState.value, 'name': service.connectedSerialDeviceName};
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    final service = context.watch<RiverInSituSamplingService>();
    final activeConnection = _getActiveConnectionDetails();
    final String? activeType = activeConnection?['type'] as String?;

    return Form(
      key: _formKey,
      child: ListView(
        padding: const EdgeInsets.all(24.0),
        children: [
          Text("Data Capture", style: Theme.of(context).textTheme.headlineSmall),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: activeType == 'bluetooth'
                    ? FilledButton.icon(
                  icon: const Icon(Icons.bluetooth_connected),
                  label: const Text("Bluetooth"),
                  onPressed: _isLoading ? null : () => _handleConnectionAttempt('bluetooth'),
                )
                    : OutlinedButton.icon(
                  icon: const Icon(Icons.bluetooth),
                  label: const Text("Bluetooth"),
                  onPressed: _isLoading ? null : () => _handleConnectionAttempt('bluetooth'),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: activeType == 'serial'
                    ? FilledButton.icon(
                  icon: const Icon(Icons.usb),
                  label: const Text("USB Serial"),
                  onPressed: _isLoading ? null : () => _handleConnectionAttempt('serial'),
                )
                    : OutlinedButton.icon(
                  icon: const Icon(Icons.usb),
                  label: const Text("USB Serial"),
                  onPressed: _isLoading ? null : () => _handleConnectionAttempt('serial'),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          if (activeConnection != null)
            _buildConnectionCard(
              type: activeConnection['type'],
              connectionState: activeConnection['state'],
              deviceName: activeConnection['name'],
            ),
          const SizedBox(height: 24),

          ValueListenableBuilder<String?>(
            valueListenable: service.sondeId,
            builder: (context, sondeId, child) {
              final newSondeId = sondeId ?? '';
              WidgetsBinding.instance.addPostFrameCallback((_) {
                if (mounted && _sondeIdController.text != newSondeId) {
                  _sondeIdController.text = newSondeId;
                  widget.data.sondeId = newSondeId;
                }
              });

              return TextFormField(
                controller: _sondeIdController,
                decoration: const InputDecoration(
                    labelText: 'Sonde ID *',
                    hintText: 'Connect device or enter manually'),
                validator: (v) => v == null || v.isEmpty ? 'Sonde ID is required' : null,
                onChanged: (value) {
                  widget.data.sondeId = value;
                },
                onSaved: (v) => widget.data.sondeId = v,
              );
            },
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(child: TextFormField(controller: _dateController, readOnly: true, decoration: const InputDecoration(labelText: 'Date'))),
              const SizedBox(width: 16),
              Expanded(child: TextFormField(controller: _timeController, readOnly: true, decoration: const InputDecoration(labelText: 'Time'))),
            ],
          ),
          const Divider(height: 32),

          Column(
            children: _parameters.map((param) {
              return _buildParameterListItem(
                icon: param['icon'] as IconData,
                label: param['label'] as String,
                unit: param['unit'] as String,
                controller: param['controller'] as TextEditingController,
              );
            }).toList(),
          ),

          const Divider(height: 32),
          // --- START: Flowrate Section ---
          _buildFlowrateSection(),
          // --- END: Flowrate Section ---

          const SizedBox(height: 32),
          ElevatedButton(
            onPressed: _goToNextStep,
            style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16)),
            child: const Text('Next'),
          ),
        ],
      ),
    );
  }

  Widget _buildParameterListItem({
    required IconData icon,
    required String label,
    required String unit,
    required TextEditingController controller,
  }) {
    final bool isMissing = controller.text.isEmpty || controller.text.contains('-999');
    final String displayValue = isMissing ? '-.--' : controller.text;
    final String displayLabel = unit.isEmpty ? label : '$label ($unit)';

    return Card(
      margin: const EdgeInsets.symmetric(vertical: 4.0),
      child: ListTile(
        leading: Icon(icon, color: Theme.of(context).primaryColor, size: 32),
        title: Text(displayLabel),
        trailing: Text(
          displayValue,
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.bold,
              color: isMissing ? Colors.grey : Theme.of(context).colorScheme.primary),
        ),
      ),
    );
  }

  Widget _buildConnectionCard({required String type, required dynamic connectionState, String? deviceName}) {
    final isConnected = connectionState == BluetoothConnectionState.connected || connectionState == SerialConnectionState.connected;
    final isConnecting = connectionState == BluetoothConnectionState.connecting || connectionState == SerialConnectionState.connecting;
    Color statusColor = isConnected ? Colors.green : Colors.red;
    String statusText = isConnected ? 'Connected to ${deviceName ?? 'device'}' : 'Disconnected';
    if (isConnecting) {
      statusColor = Colors.orange;
      statusText = 'Connecting...';
    }
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Text(statusText, style: TextStyle(color: statusColor, fontWeight: FontWeight.bold, fontSize: 16)),
            const SizedBox(height: 16),
            if (isConnecting || _isLoading)
              const CircularProgressIndicator()
            else if (isConnected)
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  ElevatedButton.icon(
                    icon: Icon(_isAutoReading ? Icons.stop_circle_outlined : Icons.play_circle_outlined),
                    label: Text(_isAutoReading ? 'Stop Reading' : 'Start Reading'),
                    onPressed: () => _toggleAutoReading(type),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _isAutoReading ? Colors.orange : Colors.green,
                      foregroundColor: Colors.white,
                    ),
                  ),
                  TextButton.icon(
                    icon: const Icon(Icons.link_off),
                    label: const Text('Disconnect'),
                    onPressed: () => _disconnect(type),
                    style: TextButton.styleFrom(foregroundColor: Colors.red),
                  )
                ],
              )
          ],
        ),
      ),
    );
  }

  // ADDED: Widget for the entire Flowrate section
  Widget _buildFlowrateSection() {
    return Card(
      margin: const EdgeInsets.symmetric(vertical: 4.0),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("Flowrate", style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildFlowrateRadioButton("Surface Drifter"),
                _buildFlowrateRadioButton("Flowmeter"),
                _buildFlowrateRadioButton("NA"),
              ],
            ),
            if (_selectedFlowrateMethod == 'Surface Drifter')
              _buildSurfaceDrifterFields(),
            if (_selectedFlowrateMethod == 'Flowmeter')
              _buildFlowmeterField(),
            if (_selectedFlowrateMethod == 'NA')
              _buildNAField(),
          ],
        ),
      ),
    );
  }

  Widget _buildFlowrateRadioButton(String title) {
    return Column(
      children: [
        Radio<String>(
          value: title,
          groupValue: _selectedFlowrateMethod,
          onChanged: _onFlowrateMethodChanged,
        ),
        Text(title),
      ],
    );
  }

  Widget _buildSurfaceDrifterFields() {
    return Padding(
      padding: const EdgeInsets.only(top: 16.0),
      child: Column(
        children: [
          TextFormField(
            controller: _sdHeightController,
            decoration: const InputDecoration(labelText: 'Height (m)'),
            keyboardType: TextInputType.number,
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _sdDistanceController,
            decoration: const InputDecoration(labelText: 'Distance (m)'),
            keyboardType: TextInputType.number,
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _sdTimeFirstController,
            decoration: const InputDecoration(labelText: 'Time First Deploy (HH:mm:ss)', suffixIcon: Icon(Icons.timer)),
            readOnly: true,
            onTap: () => _selectTime(context, _sdTimeFirstController),
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _sdTimeLastController,
            decoration: const InputDecoration(labelText: 'Time Last Deploy (HH:mm:ss)', suffixIcon: Icon(Icons.timer)),
            readOnly: true,
            onTap: () => _selectTime(context, _sdTimeLastController),
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: _calculateFlowrate,
            child: const Text('Get Flowrate'),
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _flowrateValueController,
            decoration: const InputDecoration(labelText: 'Flowrate (m/s)'),
            readOnly: true,
          ),
        ],
      ),
    );
  }

  Widget _buildFlowmeterField() {
    return Padding(
      padding: const EdgeInsets.only(top: 16.0),
      child: TextFormField(
        controller: _flowrateValueController,
        decoration: const InputDecoration(labelText: 'Flowrate (m/s)'),
        keyboardType: TextInputType.number,
      ),
    );
  }

  Widget _buildNAField() {
    return Padding(
      padding: const EdgeInsets.only(top: 16.0),
      child: TextFormField(
        controller: _flowrateValueController,
        decoration: const InputDecoration(labelText: 'Flowrate (m/s)'),
        readOnly: true,
      ),
    );
  }
}
