import 'dart:async';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:toggle_switch/toggle_switch.dart';
import '../../../../../auth_provider.dart';
import '../../../../models/marine_manual_pre_departure_checklist_data.dart';
import '../../../../services/marine_manual_pre_departure_service.dart';

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

  @override
  _MarineManualPreDepartureChecklistScreenState createState() =>
      _MarineManualPreDepartureChecklistScreenState();
}

class _MarineManualPreDepartureChecklistScreenState
    extends State<MarineManualPreDepartureChecklistScreen> {
  final _data = MarineManualPreDepartureChecklistData();
  bool _isLoading = false;

  final Map<String, bool> _remarksVisibility = {};

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


  final List<String> _checklistItemsText = [
    'MMWQM Standard Operation Procedure (SOP)',
    'Back-up Sampling Sheet and Chain of Custody form',
    'YSI EXO2 Sonde Include Sensor (pH/Turbidity/Conductivity/Dissolved Oxygen)',
    'Varn Dorn Sampler with Rope and Messenger',
    'Laptop',
    'Smart pre-installed with application (apps for manual sampling - MMS)',
    'GPS Navigation',
    'Calibration standards (pH/Turbidity/Conductivity)',
    'Distilled water (D.I)',
    'Universal pH Indicator paper',
    'Personal Floating Devices (PFD)',
    'First aid kits',
    'Sampling Shoes',
    'Sufficient set of cooler box and sampling bottles',
    'Ice packets',
    'Disposable gloves',
    'Black plastic bags',
    'Maker pen, pen and brown tapes',
    'Zipper Bags',
    'Aluminium Foil',
  ];

  @override
  void initState() {
    super.initState();
    for (var item in _checklistItemsText) {
      _data.checklistItems[item] = false;
      _data.remarks[item] = '';
      _remarksVisibility[item] = false;
    }

    // NEW: Check initial connection and start listening for changes
    _checkInitialConnectivity();
    _connectivitySubscription =
        Connectivity().onConnectivityChanged.listen(_updateConnectionStatus);
  }

  // NEW: Dispose the connectivity listener to prevent memory leaks
  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  // NEW: Method to check the first time the screen loads
  Future<void> _checkInitialConnectivity() async {
    final connectivityResult = await Connectivity().checkConnectivity();
    _updateConnectionStatus(connectivityResult);
  }

  // NEW: Callback method to update UI based on connectivity changes
  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 {
    setState(() => _isLoading = true);

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

      _data.reporterUserId = auth.profileData?['user_id'];
      _data.reporterName = auth.profileData?['user_name'];
      _data.submissionDate = DateTime.now().toIso8601String().split('T').first;

      final result = await service.submitChecklist(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('Pre-Departure Checklist (F-MM03)'),
      ),
      body: Column(
        children: [
          // NEW: Offline banner that shows when there's no internet
          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: SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                children: [
                  ListView.separated(
                    physics: const NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    itemCount: _checklistItemsText.length,
                    itemBuilder: (context, index) {
                      final item = _checklistItemsText[index];
                      return _buildChecklistItem(item);
                    },
                    separatorBuilder: (context, index) => const SizedBox(height: 8),
                  ),
                  const SizedBox(height: 24),
                  const Divider(),
                  const SizedBox(height: 10),
                  Row(
                    children: [
                      Expanded(
                        child: OutlinedButton(
                          onPressed: () => Navigator.of(context).pop(),
                          child: const Text('Cancel'),
                        ),
                      ),
                      const SizedBox(width: 10.0),
                      Expanded(
                        child: ElevatedButton(
                          // NEW: Submit button is disabled when loading OR offline
                          onPressed: _isLoading || !_isOnline ? null : _submit,
                          child: _isLoading
                              ? const CircularProgressIndicator(color: Colors.white)
                              : const Text('Submit'),
                        ),
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildChecklistItem(String title) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(
                  child: Text(
                    title,
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                ),
                const SizedBox(width: 16),
                ToggleSwitch(
                  minWidth: 70.0,
                  cornerRadius: 20.0,
                  activeBgColor: [Theme.of(context).colorScheme.primary],
                  activeFgColor: Colors.white,
                  inactiveBgColor: Colors.grey[700],
                  inactiveFgColor: Colors.white,
                  initialLabelIndex: _data.checklistItems[title]! ? 0 : 1,
                  totalSwitches: 2,
                  labels: const ['Yes', 'No'],
                  radiusStyle: true,
                  onToggle: (index) {
                    setState(() {
                      _data.checklistItems[title] = index == 0;
                    });
                  },
                ),
              ],
            ),
            const SizedBox(height: 8),
            if (_remarksVisibility[title]!)
              TextFormField(
                initialValue: _data.remarks[title],
                decoration: const InputDecoration(
                  labelText: 'Remarks',
                  contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  border: OutlineInputBorder(),
                ),
                onChanged: (value) {
                  _data.remarks[title] = value;
                },
              ),
            Align(
              alignment: Alignment.centerRight,
              child: TextButton.icon(
                onPressed: () {
                  setState(() {
                    _remarksVisibility[title] = !_remarksVisibility[title]!;
                  });
                },
                icon: Icon(
                  _remarksVisibility[title]!
                      ? Icons.remove_circle_outline
                      : Icons.add_comment_outlined,
                  size: 16,
                ),
                label: Text(
                  _data.remarks[title]!.isNotEmpty
                      ? 'Edit Remarks'
                      : 'Add Remarks',
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}