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_sonde_calibration_data.dart';
import '../../../../services/marine_manual_sonde_calibration_service.dart';

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

  @override
  State<MarineManualSondeCalibrationScreen> createState() =>
      _MarineManualSondeCalibrationScreenState();
}

class _MarineManualSondeCalibrationScreenState
    extends State<MarineManualSondeCalibrationScreen> {
  final _formKey = GlobalKey<FormState>();
  final _data = MarineManualSondeCalibrationData();
  bool _isLoading = false;

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

  // Scroll controller to move to top on error
  final _scrollController = ScrollController();

  // --- Controllers for all fields ---
  final _sondeSerialController = TextEditingController();
  final _firmwareController = TextEditingController();
  final _korController = TextEditingController();
  // Location is now a dropdown, no controller needed, will save to _data
  final _startDateTimeController = TextEditingController();
  final _endDateTimeController = TextEditingController();
  final _remarksController = TextEditingController();

  // pH Controllers
  final _ph7MvController = TextEditingController();
  final _ph7BeforeController = TextEditingController();
  final _ph7AfterController = TextEditingController();
  final _ph10MvController = TextEditingController();
  final _ph10BeforeController = TextEditingController();
  final _ph10AfterController = TextEditingController();

  // Other parameter controllers
  final _condBeforeController = TextEditingController();
  final _condAfterController = TextEditingController();
  final _doBeforeController = TextEditingController();
  final _doAfterController = TextEditingController();
  final _turbidity0BeforeController = TextEditingController();
  final _turbidity0AfterController = TextEditingController();
  final _turbidity124BeforeController = TextEditingController();
  final _turbidity124AfterController = TextEditingController();

  // --- Focus Nodes for all fields (to allow focus on error) ---
  // We don't actively use them to redirect, but they are good practice
  // and necessary for the form to manage focus.
  final _sondeSerialFocusNode = FocusNode();
  final _firmwareFocusNode = FocusNode();
  final _korFocusNode = FocusNode();
  final _locationFocusNode = FocusNode();
  final _startDateTimeFocusNode = FocusNode();
  final _endDateTimeFocusNode = FocusNode();
  final _remarksFocusNode = FocusNode();
  final _statusFocusNode = FocusNode();

  final _ph7MvFocusNode = FocusNode();
  final _ph7BeforeFocusNode = FocusNode();
  final _ph7AfterFocusNode = FocusNode();
  final _ph10MvFocusNode = FocusNode();
  final _ph10BeforeFocusNode = FocusNode();
  final _ph10AfterFocusNode = FocusNode();

  final _condBeforeFocusNode = FocusNode();
  final _condAfterFocusNode = FocusNode();
  final _doBeforeFocusNode = FocusNode();
  final _doAfterFocusNode = FocusNode();
  final _turbidity0BeforeFocusNode = FocusNode();
  final _turbidity0AfterFocusNode = FocusNode();
  final _turbidity124BeforeFocusNode = FocusNode();
  final _turbidity124AfterFocusNode = FocusNode();
  // ---

  @override
  void initState() {
    super.initState();
    _startDateTimeController.text =
        DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now());
    _checkInitialConnectivity();
    _connectivitySubscription =
        Connectivity().onConnectivityChanged.listen(_updateConnectionStatus);
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    _scrollController.dispose();

    // Dispose all controllers
    _sondeSerialController.dispose();
    _firmwareController.dispose();
    _korController.dispose();
    _startDateTimeController.dispose();
    _endDateTimeController.dispose();
    _remarksController.dispose();
    _ph7MvController.dispose();
    _ph7BeforeController.dispose();
    _ph7AfterController.dispose();
    _ph10MvController.dispose();
    _ph10BeforeController.dispose();
    _ph10AfterController.dispose();
    _condBeforeController.dispose();
    _condAfterController.dispose();
    _doBeforeController.dispose();
    _doAfterController.dispose();
    _turbidity0BeforeController.dispose();
    _turbidity0AfterController.dispose();
    _turbidity124BeforeController.dispose();
    _turbidity124AfterController.dispose();

    // Dispose all focus nodes
    _sondeSerialFocusNode.dispose();
    _firmwareFocusNode.dispose();
    _korFocusNode.dispose();
    _locationFocusNode.dispose();
    _startDateTimeFocusNode.dispose();
    _endDateTimeFocusNode.dispose();
    _remarksFocusNode.dispose();
    _statusFocusNode.dispose();
    _ph7MvFocusNode.dispose();
    _ph7BeforeFocusNode.dispose();
    _ph7AfterFocusNode.dispose();
    _ph10MvFocusNode.dispose();
    _ph10BeforeFocusNode.dispose();
    _ph10AfterFocusNode.dispose();
    _condBeforeFocusNode.dispose();
    _condAfterFocusNode.dispose();
    _doBeforeFocusNode.dispose();
    _doAfterFocusNode.dispose();
    _turbidity0BeforeFocusNode.dispose();
    _turbidity0AfterFocusNode.dispose();
    _turbidity124BeforeFocusNode.dispose();
    _turbidity124AfterFocusNode.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,
        ));
      }
    }
  }

  // --- Validation Helper Methods ---
  String? _validateRequired(String? val) {
    if (val == null || val.isEmpty) {
      return 'This field is required';
    }
    return null;
  }

  String? _validateNumeric(String? val) {
    if (val == null || val.isEmpty) {
      return 'This field is required';
    }
    if (double.tryParse(val) == null) {
      return 'Must be a valid number';
    }
    return null;
  }

  String? _validateDropdown(String? val) {
    if (val == null || val.isEmpty) {
      return 'Please select an option';
    }
    return null;
  }

  // --- NEW: Error Dialog ---
  Future<void> _showErrorDialog() async {
    return showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Submission Failed'),
          content: const SingleChildScrollView(
            child: Text(
                'Please fill in all required fields. Errors are highlighted in red.'),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('OK'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Future<void> _selectDateTime(TextEditingController controller) async {
    final date = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );
    if (date == null) return;

    final time = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.fromDateTime(DateTime.now()),
    );
    if (time == null) return;

    final dateTime =
    DateTime(date.year, date.month, date.day, time.hour, time.minute);
    controller.text = DateFormat('yyyy-MM-dd HH:mm').format(dateTime);
  }

  Future<void> _submit() async {
    // Check form validity
    if (!_formKey.currentState!.validate()) {
      // If invalid, show dialog and scroll to top
      _showErrorDialog();
      _scrollController.animateTo(
        0.0,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
      return;
    }

    // If valid, save form data and set loading state
    _formKey.currentState!.save();
    setState(() => _isLoading = true);

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

      // Populate _data object from controllers
      _data.calibratedByUserId = auth.profileData?['user_id'];
      _data.sondeSerialNumber = _sondeSerialController.text;
      _data.firmwareVersion = _firmwareController.text;
      _data.korVersion = _korController.text;
      // _data.location is already set by onSaved
      _data.startDateTime = _startDateTimeController.text;
      _data.endDateTime = _endDateTimeController.text;
      // _data.calibrationStatus is already set by onSaved
      _data.remarks = _remarksController.text;

      // Populate numeric values
      _data.ph7Mv = double.tryParse(_ph7MvController.text);
      _data.ph7Before = double.tryParse(_ph7BeforeController.text);
      _data.ph7After = double.tryParse(_ph7AfterController.text);
      _data.ph10Mv = double.tryParse(_ph10MvController.text);
      _data.ph10Before = double.tryParse(_ph10BeforeController.text);
      _data.ph10After = double.tryParse(_ph10AfterController.text);
      _data.condBefore = double.tryParse(_condBeforeController.text);
      _data.condAfter = double.tryParse(_condAfterController.text);
      _data.doBefore = double.tryParse(_doBeforeController.text);
      _data.doAfter = double.tryParse(_doAfterController.text);
      _data.turbidity0Before =
          double.tryParse(_turbidity0BeforeController.text);
      _data.turbidity0After = double.tryParse(_turbidity0AfterController.text);
      _data.turbidity124Before =
          double.tryParse(_turbidity124BeforeController.text);
      _data.turbidity124After =
          double.tryParse(_turbidity124AfterController.text);

      final result =
      await service.submitCalibration(data: _data, authProvider: auth);

      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('Sonde Calibration Form (F-MM02)'),
      ),
      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: TextStyle(color: Colors.white),
                textAlign: TextAlign.center,
              ),
            ),
          Expanded(
            child: Form(
              key: _formKey,
              // Autovalidate after the first submit attempt
              autovalidateMode: AutovalidateMode.disabled,
              child: SingleChildScrollView(
                controller: _scrollController, // Added scroll controller
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    _buildGeneralInfoCard(),
                    const SizedBox(height: 16),
                    _buildCalibrationTableCard(),
                    const SizedBox(height: 16),
                    _buildSummaryCard(),
                    const SizedBox(height: 24),
                    Row(
                      children: [
                        Expanded(
                            child: OutlinedButton(
                                onPressed: () => Navigator.of(context).pop(),
                                child: const Text('Cancel'))),
                        const SizedBox(width: 10.0),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _isLoading || !_isOnline ? null : _submit,
                            child: _isLoading
                                ? const CircularProgressIndicator(
                                color: Colors.white)
                                : const Text('Submit'),
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildGeneralInfoCard() {
    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('General Information',
                style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 16),
            TextFormField(
              controller: _sondeSerialController,
              focusNode: _sondeSerialFocusNode,
              decoration: const InputDecoration(
                  labelText: 'Sonde Serial Number *',
                  border: OutlineInputBorder()),
              validator: _validateRequired, // Use helper
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _firmwareController,
                    focusNode: _firmwareFocusNode,
                    decoration: const InputDecoration(
                        labelText: 'Firmware Version *', // Made required
                        border: OutlineInputBorder()),
                    validator: _validateRequired, // Added validator
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: TextFormField(
                    controller: _korController,
                    focusNode: _korFocusNode,
                    decoration: const InputDecoration(
                        labelText: 'KOR Version *', // Made required
                        border: OutlineInputBorder()),
                    validator: _validateRequired, // Added validator
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            // --- MODIFIED: Location Dropdown ---
            DropdownButtonFormField<String>(
              focusNode: _locationFocusNode,
              decoration: const InputDecoration(
                  labelText: 'Location *', border: OutlineInputBorder()),
              items: ['HQ', 'Regional'].map((String value) {
                return DropdownMenuItem<String>(value: value, child: Text(value));
              }).toList(),
              onChanged: (val) {
                _data.location = val;
              },
              onSaved: (val) => _data.location = val,
              validator: _validateDropdown, // Use dropdown validator
            ),
            // ---
            const SizedBox(height: 16),
            TextFormField(
              controller: _startDateTimeController,
              focusNode: _startDateTimeFocusNode,
              readOnly: true,
              decoration: const InputDecoration(
                  labelText: 'Start Date/Time *',
                  border: OutlineInputBorder(),
                  suffixIcon: Icon(Icons.calendar_month)),
              onTap: () => _selectDateTime(_startDateTimeController),
              validator: _validateRequired, // Use helper
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _endDateTimeController,
              focusNode: _endDateTimeFocusNode,
              readOnly: true,
              decoration: const InputDecoration(
                  labelText: 'End Date/Time *',
                  border: OutlineInputBorder(),
                  suffixIcon: Icon(Icons.calendar_month)),
              onTap: () => _selectDateTime(_endDateTimeController),
              validator: _validateRequired, // Use helper
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCalibrationTableCard() {
    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('Calibration Parameters',
                style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 16),
            _buildSectionHeader('pH'),
            _buildParameterRowThreeColumn(
              'pH 7.00 (mV 0+30)',
              mvController: _ph7MvController,
              beforeController: _ph7BeforeController,
              afterController: _ph7AfterController,
              mvFocusNode: _ph7MvFocusNode,
              beforeFocusNode: _ph7BeforeFocusNode,
              afterFocusNode: _ph7AfterFocusNode,
            ),
            _buildParameterRowThreeColumn(
              'pH 10.00 (mV-180+30)',
              mvController: _ph10MvController,
              beforeController: _ph10BeforeController,
              afterController: _ph10AfterController,
              mvFocusNode: _ph10MvFocusNode,
              beforeFocusNode: _ph10BeforeFocusNode,
              afterFocusNode: _ph10AfterFocusNode,
            ),
            const Divider(height: 24),
            _buildSectionHeader('SP Conductivity (µS/cm)'),
            _buildParameterRowTwoColumn(
              '50,000 (Marine)',
              beforeController: _condBeforeController,
              afterController: _condAfterController,
              beforeFocusNode: _condBeforeFocusNode,
              afterFocusNode: _condAfterFocusNode,
            ),
            const Divider(height: 24),
            _buildSectionHeader('Turbidity (NTU)'),
            _buildParameterRowTwoColumn(
              '0.0 (D.I.)',
              beforeController: _turbidity0BeforeController,
              afterController: _turbidity0AfterController,
              beforeFocusNode: _turbidity0BeforeFocusNode,
              afterFocusNode: _turbidity0AfterFocusNode,
            ),
            _buildParameterRowTwoColumn(
              '124 (Marine)',
              beforeController: _turbidity124BeforeController,
              afterController: _turbidity124AfterController,
              beforeFocusNode: _turbidity124BeforeFocusNode,
              afterFocusNode: _turbidity124AfterFocusNode,
            ),
            const Divider(height: 24),
            _buildSectionHeader('Dissolved Oxygen (%)'),
            _buildParameterRowTwoColumn(
              '100.0 (Air Saturated)',
              beforeController: _doBeforeController,
              afterController: _doAfterController,
              beforeFocusNode: _doBeforeFocusNode,
              afterFocusNode: _doAfterFocusNode,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionHeader(String title) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0),
      child: Text(title, style: Theme.of(context).textTheme.titleMedium),
    );
  }

  Widget _buildParameterRowThreeColumn(
      String label, {
        required TextEditingController mvController,
        required TextEditingController beforeController,
        required TextEditingController afterController,
        required FocusNode mvFocusNode,
        required FocusNode beforeFocusNode,
        required FocusNode afterFocusNode,
      }) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                  child: TextFormField(
                    controller: mvController,
                    focusNode: mvFocusNode,
                    decoration: const InputDecoration(
                        labelText: 'MV Reading *', border: OutlineInputBorder()),
                    keyboardType: TextInputType.number,
                    validator: _validateNumeric, // Added validator
                  )),
              const SizedBox(width: 8),
              Expanded(
                  child: TextFormField(
                    controller: beforeController,
                    focusNode: beforeFocusNode,
                    decoration: const InputDecoration(
                        labelText: 'Before Cal *', border: OutlineInputBorder()),
                    keyboardType: TextInputType.number,
                    validator: _validateNumeric, // Added validator
                  )),
              const SizedBox(width: 8),
              Expanded(
                  child: TextFormField(
                    controller: afterController,
                    focusNode: afterFocusNode,
                    decoration: const InputDecoration(
                        labelText: 'After Cal *', border: OutlineInputBorder()),
                    keyboardType: TextInputType.number,
                    validator: _validateNumeric, // Added validator
                  )),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildParameterRowTwoColumn(
      String label, {
        required TextEditingController beforeController,
        required TextEditingController afterController,
        required FocusNode beforeFocusNode,
        required FocusNode afterFocusNode,
      }) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                  child: TextFormField(
                    controller: beforeController,
                    focusNode: beforeFocusNode,
                    decoration: const InputDecoration(
                        labelText: 'Before Cal *', border: OutlineInputBorder()),
                    keyboardType: TextInputType.number,
                    validator: _validateNumeric, // Added validator
                  )),
              const SizedBox(width: 8),
              Expanded(
                  child: TextFormField(
                    controller: afterController,
                    focusNode: afterFocusNode,
                    decoration: const InputDecoration(
                        labelText: 'After Cal *', border: OutlineInputBorder()),
                    keyboardType: TextInputType.number,
                    validator: _validateNumeric, // Added validator
                  )),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSummaryCard() {
    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('Summary', style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 16),
            DropdownButtonFormField<String>(
              focusNode: _statusFocusNode,
              decoration: const InputDecoration(
                  labelText: 'Overall Status *', border: OutlineInputBorder()),
              items: ['Pass', 'Fail', 'Pass with Warning'].map((String value) {
                return DropdownMenuItem<String>(value: value, child: Text(value));
              }).toList(),
              onChanged: (val) {
                _data.calibrationStatus = val;
              },
              onSaved: (val) => _data.calibrationStatus = val,
              validator: _validateDropdown, // Use dropdown validator
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _remarksController,
              focusNode: _remarksFocusNode,
              decoration: const InputDecoration(
                  labelText: 'Comment/Observation *', // Made required
                  border: OutlineInputBorder()),
              maxLines: 3,
              validator: _validateRequired, // Added validator
            ),
          ],
        ),
      ),
    );
  }
}