// lib/screens/air/manual/air_manual_collection_screen.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:dropdown_search/dropdown_search.dart';

import '../../../auth_provider.dart';
import '../../../models/air_installation_data.dart';
import '../../../models/air_collection_data.dart';
import '../../../services/air_sampling_service.dart';
import 'widgets/air_manual_collection.dart'; // The form widget

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

  @override
  State<AirManualCollectionScreen> createState() =>
      _AirManualCollectionScreenState();
}

class _AirManualCollectionScreenState extends State<AirManualCollectionScreen> {
  late Future<List<AirInstallationData>> _pendingInstallationsFuture;
  AirInstallationData? _selectedInstallation;
  AirCollectionData _collectionData = AirCollectionData();
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    // Fetch the list of pending installations when the screen loads
    _pendingInstallationsFuture =
        Provider.of<AirSamplingService>(context, listen: false)
            .getPendingInstallations();
  }

  // MODIFIED: This method now fetches appSettings and passes it to the service.
  Future<void> _submitCollection() async {
    if (_selectedInstallation == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Please select an installation first.')),
      );
      return;
    }
    setState(() => _isLoading = true);

    // Get the required services and providers.
    final service = Provider.of<AirSamplingService>(context, listen: false);
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final appSettings = authProvider.appSettings;

    // Pass the selected installation data and appSettings to the service.
    final result = await service.submitCollection(_collectionData, _selectedInstallation!, appSettings);

    setState(() => _isLoading = false);

    if (!mounted) return;

    final message = result['message'] ?? 'An unknown error occurred.';
    final color = (result['status'] == 'L3' || result['status'] == 'S3')
        ? Colors.green
        : Colors.red;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: color),
    );

    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Air Sampling Collection'),
      ),
      body: FutureBuilder<List<AirInstallationData>>(
        future: _pendingInstallationsFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            return Center(child: Text('Error: ${snapshot.error}'));
          }
          if (!snapshot.hasData || snapshot.data!.isEmpty) {
            return const Center(
                child: Text('No pending installations found.'));
          }

          final pendingInstallations = snapshot.data!;

          return Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: DropdownSearch<AirInstallationData>(
                  items: pendingInstallations,
                  itemAsString: (AirInstallationData u) =>
                  "${u.stationID} - ${u.locationName} (${u.installationDate} ${u.installationTime ?? ''})",
                  popupProps: const PopupProps.menu(
                    showSearchBox: true,
                    searchFieldProps: TextFieldProps(
                      decoration: InputDecoration(
                        labelText: 'Search Installation',
                        border: OutlineInputBorder(),
                      ),
                    ),
                  ),
                  dropdownDecoratorProps: const DropDownDecoratorProps(
                    dropdownSearchDecoration: InputDecoration(
                      labelText: "Select Pending Installation",
                      border: OutlineInputBorder(),
                    ),
                  ),
                  onChanged: (AirInstallationData? data) {
                    setState(() {
                      _selectedInstallation = data;
                      // When an installation is selected, prepare the collection data object
                      if (data != null) {
                        _collectionData = AirCollectionData(
                          installationRefID: data.refID,
                          airManId: data.airManId, // Pass the server ID
                          collectionUserId:
                          authProvider.profileData?['user_id'],
                        );
                      } else {
                        _collectionData = AirCollectionData();
                      }
                    });
                  },
                  selectedItem: _selectedInstallation,
                ),
              ),
              const Divider(),
              Expanded(
                child: _selectedInstallation != null
                    ? AirManualCollectionWidget(
                  key: ValueKey(_selectedInstallation!
                      .refID), // Ensures widget rebuilds
                  stationCode: _selectedInstallation!.stationID!,
                  data: _collectionData,
                  initialTemp: double.tryParse(
                      _selectedInstallation!.temp ?? '0.0') ??
                      0.0,
                  onSubmit: _submitCollection,
                  isLoading: _isLoading,
                )
                    : const Center(
                    child:
                    Text('Please select an installation to proceed.')),
              ),
            ],
          );
        },
      ),
    );
  }
}