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 = {};

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

  // All checklist items from the PDF are now grouped
  final Map<String, List<String>> _checklistSections = {
    'INTERNAL - IN-SITU SAMPLING': [ // Section title matches PDF
      'Marine manual Standard Operation Procedure (SOP)', // Item text matches PDF
      'Back-up Sampling Sheet & Chain of Custody form', // Item text matches PDF
      'Calibration worksheet', // Item text matches PDF
      'YSI EXO 2 Sonde include sensor (pH/Turbidity/Conductivity/Dissolved Oxygen)', // Item text matches PDF
      'Spare set sensor (pH/Turbidity/Conductivity/Dissolved Oxygen)', // Item text matches PDF
      'YSI serial cable', // Item text matches PDF
      'Van Dorn Sampler (with rope & messenger)', // Item text matches PDF
      'Laptop', // Item text matches PDF
      'Smartphone pre-installed with application (Apps for manual sampling-MMS)', // Item text matches PDF
      'GPS navigation', // Item text matches PDF
      'Calibration standards (pH/Turbidity/Conductivity)', // Item text matches PDF
      'Distilled water (D.I.)', // Item text matches PDF
      'Universal pH indicator paper', // Item text matches PDF
      'Alcohol swab', // Item text matches PDF
      'Personal Floating Devices (PFD)', // Item text matches PDF
      'First aid kits', // Item text matches PDF
      'Disposable gloves', // Item text matches PDF
      'Black plastic bags', // Item text matches PDF
      'Marker pen, pen, clear tapes, brown tapes & scissors', // Item text matches PDF
      'Energizer battery', // Item text matches PDF
      'EXO battery opener and EXO magnet', // Item text matches PDF
      'Laminated white paper', // Item text matches PDF
      'Clear glass bottle (blue сар)', // Item text matches PDF
      'Proper sampling attires & shoes', // Item text matches PDF
      'Raincoat/Poncho', // Item text matches PDF
      'Ice packets', // Item text matches PDF
    ],
    'INTERNAL-TARBALL SAMPLING': [ // Section title matches PDF
      'Measuring tape (100 meter)', // Item text matches PDF
      'Steel raking', // Item text matches PDF
      'Aluminum foil', // Item text matches PDF
      'Zipper bags', // Item text matches PDF
    ],
    'EXTERNAL - LABORATORY': [ // Section title matches PDF
      'Sufficient sets of cooler box and sampling bottles with label', // Item text matches PDF
      'Field duplicate sampling bottles (if any)', // Item text matches PDF
      'Blank samples sampling bottles (if any)', // Item text matches PDF
      'Preservatives (acid & alkaline)', // Item text matches PDF
    ],
  };

  @override
  void initState() {
    super.initState();
    // Iterate through the map structure to initialize data
    _checklistSections.forEach((section, items) {
      for (var item in items) {
        _data.checklistItems[item] = false; // MODIFIED: Default to 'No' (false)
        _data.remarks[item] = '';
        _remarksVisibility[item] = false;
      }
    });

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

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    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 {
    // No form validation needed as Project/Month fields removed

    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']; // Use user_name as reporterName
      _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: [
          // Offline banner
          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: [
                  // Build UI from the section map
                  ..._buildSectionWidgets(),

                  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(
                          onPressed:
                          _isLoading || !_isOnline ? null : _submit,
                          child: _isLoading
                              ? const CircularProgressIndicator(
                              color: Colors.white)
                              : const Text('Submit'),
                        ),
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // Helper method to build the list of sections and their items
  List<Widget> _buildSectionWidgets() {
    List<Widget> widgets = [];
    _checklistSections.forEach((title, items) {
      // Add the section header
      widgets.add(
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 16.0),
          child: Text(
            title,
            style: Theme.of(context).textTheme.titleLarge,
          ),
        ),
      );

      // Add the list of items for this section
      widgets.add(
        ListView.separated(
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: items.length,
          itemBuilder: (context, index) {
            final item = items[index];
            return _buildChecklistItem(item);
          },
          separatorBuilder: (context, index) => const SizedBox(height: 8),
        ),
      );
    });
    return widgets;
  }

  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,
                  // Use theme colors
                  activeBgColor: [Theme.of(context).colorScheme.primary],
                  activeFgColor: Colors.white, // Keep white for contrast on primary
                  inactiveBgColor: Colors.grey[700], // Dark theme inactive
                  inactiveFgColor: Colors.white, // White for contrast on dark grey
                  // MODIFIED: Logic reversed for ['No', 'Yes']
                  initialLabelIndex: _data.checklistItems[title]! ? 1 : 0, // No: 0, Yes: 1
                  totalSwitches: 2,
                  labels: const ['No', 'Yes'], // MODIFIED: Swapped labels
                  radiusStyle: true,
                  onToggle: (index) {
                    setState(() {
                      _data.checklistItems[title] = index == 1; // MODIFIED: 1 is Yes (true), 0 is No (false)
                    });
                  },
                ),
              ],
            ),
            const SizedBox(height: 8),
            if (_remarksVisibility[title]!)
              TextFormField(
                initialValue: _data.remarks[title],
                // Rely on theme for input decoration
                decoration: const InputDecoration(
                  labelText: 'Remarks',
                  contentPadding:
                  EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  border: OutlineInputBorder(),
                  alignLabelWithHint: true, // Improves look for multi-line
                ),
                maxLines: 3, // Allow multiple lines for remarks
                onChanged: (value) {
                  // Save remarks as user types, no need for onSaved with controllers
                  _data.remarks[title] = value;
                },
              ),
            Align(
              alignment: Alignment.centerRight,
              child: TextButton.icon(
                onPressed: () {
                  setState(() {
                    _remarksVisibility[title] = !_remarksVisibility[title]!;
                  });
                },
                // Use theme icon color implicitly
                icon: Icon(
                  _remarksVisibility[title]!
                      ? Icons.remove_circle_outline
                      : Icons.add_comment_outlined,
                  size: 16,
                ),
                // Use theme text color implicitly
                label: Text(
                  _remarksVisibility[title]!
                      ? 'Hide Remarks' // Change label when visible
                      : (_data.remarks[title]!.isNotEmpty
                      ? 'Edit Remarks'
                      : 'Add Remarks'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}