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_equipment_maintenance_data.dart';
import '../../../../services/marine_manual_equipment_maintenance_service.dart';

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

  @override
  State<MarineManualEquipmentMaintenanceScreen> createState() =>
      _MarineManualEquipmentMaintenanceScreenState();
}

class _MarineManualEquipmentMaintenanceScreenState
    extends State<MarineManualEquipmentMaintenanceScreen> {
  final _formKey = GlobalKey<FormState>();
  final _data = MarineManualEquipmentMaintenanceData();
  bool _isLoading = false;

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

  final _dateController = TextEditingController();
  final _performedByController = TextEditingController();

  @override
  void initState() {
    super.initState();
    final auth = Provider.of<AuthProvider>(context, listen: false);
    _dateController.text = DateFormat('yyyy-MM-dd').format(DateTime.now());
    _performedByController.text = auth.profileData?['username'] ?? 'Unknown User';
    _checkInitialConnectivity();
    _connectivitySubscription =
        Connectivity().onConnectivityChanged.listen(_updateConnectionStatus);
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    _dateController.dispose();
    _performedByController.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()) return;
    _formKey.currentState!.save();
    setState(() => _isLoading = true);

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

      _data.performedByUserId = auth.profileData?['user_id'];
      _data.maintenanceDate = _dateController.text;

      final result = await service.submitMaintenanceReport(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('Equipment Maintenance (F-MM01)'),
      ),
      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: [
                    Card(
                      elevation: 2,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('Report Details', style: Theme.of(context).textTheme.titleLarge),
                            const SizedBox(height: 16),
                            TextFormField(
                              decoration: const InputDecoration(labelText: 'Equipment Name / ID *', border: OutlineInputBorder()),
                              validator: (val) => val == null || val.isEmpty ? 'This field is required' : null,
                              onSaved: (val) => _data.equipmentName = val,
                            ),
                            const SizedBox(height: 16),
                            TextFormField(
                              controller: _dateController,
                              readOnly: true,
                              decoration: const InputDecoration(labelText: 'Maintenance Date', border: OutlineInputBorder()),
                            ),
                            const SizedBox(height: 16),
                            DropdownButtonFormField<String>(
                              decoration: const InputDecoration(labelText: 'Maintenance Type *', border: OutlineInputBorder()),
                              items: ['Routine', 'Repair', 'Inspection', 'Replacement'].map((String value) {
                                return DropdownMenuItem<String>(value: value, child: Text(value));
                              }).toList(),
                              onChanged: (val) => _data.maintenanceType = val,
                              validator: (val) => val == null ? 'Please select a type' : null,
                            ),
                            const SizedBox(height: 16),
                            DropdownButtonFormField<String>(
                              decoration: const InputDecoration(labelText: 'Final Status *', border: OutlineInputBorder()),
                              items: ['Completed', 'Pending Parts', 'In Progress', 'Requires Follow-up'].map((String value) {
                                return DropdownMenuItem<String>(value: value, child: Text(value));
                              }).toList(),
                              onChanged: (val) => _data.status = val,
                              validator: (val) => val == null ? 'Please select a status' : null,
                            ),
                            const SizedBox(height: 16),
                            TextFormField(
                              controller: _performedByController,
                              readOnly: true,
                              decoration: const InputDecoration(labelText: 'Performed By', border: OutlineInputBorder()),
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    Card(
                      elevation: 2,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('Description & Remarks', style: Theme.of(context).textTheme.titleLarge),
                            const SizedBox(height: 16),
                            TextFormField(
                              decoration: const InputDecoration(labelText: 'Description of Work Done', border: OutlineInputBorder(), alignLabelWithHint: true),
                              maxLines: 4,
                              onSaved: (val) => _data.workDescription = val,
                            ),
                            const SizedBox(height: 16),
                            TextFormField(
                              decoration: const InputDecoration(labelText: 'Parts Replaced (if any)', border: OutlineInputBorder(), alignLabelWithHint: true),
                              maxLines: 3,
                              onSaved: (val) => _data.partsReplaced = val,
                            ),
                            const SizedBox(height: 16),
                            TextFormField(
                              decoration: const InputDecoration(labelText: 'General Remarks', border: OutlineInputBorder(), alignLabelWithHint: true),
                              maxLines: 3,
                              onSaved: (val) => _data.remarks = val,
                            ),
                          ],
                        ),
                      ),
                    ),
                    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'),
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}