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;

  // State for connectivity
  bool _isOnline = true;
  late StreamSubscription<List<ConnectivityResult>> _connectivitySubscription;

  // Text Controllers
  final _sondeIdController = TextEditingController();
  final _dateTimeController = TextEditingController();
  final _remarksController = TextEditingController();

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

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    _sondeIdController.dispose();
    _dateTimeController.dispose();
    _remarksController.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> _submit() async {
    if (!_formKey.currentState!.validate()) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text("Please fill in all required fields."),
        backgroundColor: Colors.red,
      ));
      return;
    }
    _formKey.currentState!.save();
    setState(() => _isLoading = true);

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

      _data.calibratedByUserId = auth.profileData?['user_id'];
      _data.sondeId = _sondeIdController.text;
      _data.calibrationDateTime = _dateTimeController.text;
      _data.remarks = _remarksController.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,
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    _buildGeneralInfoCard(),
                    const SizedBox(height: 16),
                    _buildCalibrationCard(
                      title: 'pH Calibration',
                      parameters: ['pH 4', 'pH 7', 'pH 10'],
                      onSave: (param, type, value) {
                        if (value == null) return;
                        if (param == 'pH 4' && type == 'Initial') _data.ph4Initial = value;
                        if (param == 'pH 4' && type == 'Calibrated') _data.ph4Calibrated = value;
                        if (param == 'pH 7' && type == 'Initial') _data.ph7Initial = value;
                        if (param == 'pH 7' && type == 'Calibrated') _data.ph7Calibrated = value;
                        if (param == 'pH 10' && type == 'Initial') _data.ph10Initial = value;
                        if (param == 'pH 10' && type == 'Calibrated') _data.ph10Calibrated = value;
                      },
                    ),
                    const SizedBox(height: 16),
                    _buildCalibrationCard(
                      title: 'Other Parameters',
                      parameters: ['Conductivity', 'Dissolved Oxygen', 'Turbidity'],
                      onSave: (param, type, value) {
                        if (value == null) return;
                        if (param == 'Conductivity' && type == 'Initial') _data.condInitial = value;
                        if (param == 'Conductivity' && type == 'Calibrated') _data.condCalibrated = value;
                        if (param == 'Dissolved Oxygen' && type == 'Initial') _data.doInitial = value;
                        if (param == 'Dissolved Oxygen' && type == 'Calibrated') _data.doCalibrated = value;
                        if (param == 'Turbidity' && type == 'Initial') _data.turbidityInitial = value;
                        if (param == 'Turbidity' && type == 'Calibrated') _data.turbidityCalibrated = value;
                      },
                    ),
                    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: _sondeIdController,
              decoration: const InputDecoration(labelText: 'Sonde ID *', border: OutlineInputBorder()),
              validator: (val) => val == null || val.isEmpty ? 'Sonde ID is required' : null,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _dateTimeController,
              readOnly: true,
              decoration: const InputDecoration(labelText: 'Calibration Date & Time', border: OutlineInputBorder()),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCalibrationCard({
    required String title,
    required List<String> parameters,
    required Function(String, String, double?) onSave,
  }) {
    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(title, style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 8),
            ...parameters.map((param) => _buildParameterRow(param, onSave)).toList(),
          ],
        ),
      ),
    );
  }

  Widget _buildParameterRow(String label, Function(String, String, double?) onSave) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          Expanded(flex: 2, child: Text(label, style: Theme.of(context).textTheme.titleMedium)),
          Expanded(
            flex: 3,
            child: Row(
              children: [
                Expanded(child: TextFormField(
                  decoration: const InputDecoration(labelText: 'Initial', border: OutlineInputBorder()),
                  keyboardType: TextInputType.number,
                  onSaved: (val) => onSave(label, 'Initial', double.tryParse(val ?? '')),
                )),
                const SizedBox(width: 8),
                Expanded(child: TextFormField(
                  decoration: const InputDecoration(labelText: 'Calibrated', border: OutlineInputBorder()),
                  keyboardType: TextInputType.number,
                  onSaved: (val) => onSave(label, 'Calibrated', double.tryParse(val ?? '')),
                )),
              ],
            ),
          ),
        ],
      ),
    );
  }

  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>(
              decoration: const InputDecoration(labelText: 'Overall Status *', border: OutlineInputBorder()),
              items: ['Pass', 'Fail', 'Pass with Issues'].map((String value) {
                return DropdownMenuItem<String>(value: value, child: Text(value));
              }).toList(),
              onChanged: (val) {
                _data.calibrationStatus = val;
              },
              validator: (val) => val == null || val.isEmpty ? 'Status is required' : null,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _remarksController,
              decoration: const InputDecoration(labelText: 'Remarks', border: OutlineInputBorder()),
              maxLines: 3,
            ),
          ],
        ),
      ),
    );
  }
}