// lib/screens/air/manual/air_manual_installation_screen.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'dart:math';
import 'package:intl/intl.dart';

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

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

  @override
  State<AirManualInstallationScreen> createState() =>
      _AirManualInstallationScreenState();
}

class _AirManualInstallationScreenState
    extends State<AirManualInstallationScreen> {
  late AirInstallationData _installationData;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();

    // Access the provider to get the current user's ID.
    // listen: false is used because we only need to read the value once in initState.
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final userId = authProvider.profileData?['user_id'];

    _installationData = AirInstallationData(
      refID: _generateRandomId(10), // Generate a unique ID for this installation
      samplingDate: DateFormat('yyyy-MM-dd').format(DateTime.now()),
      // Set the user ID from the provider. The client selection is now handled in the widget.
      installationUserId: userId,
    );
  }

  String _generateRandomId(int length) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    final rnd = Random();
    return String.fromCharCodes(Iterable.generate(
        length, (_) => chars.codeUnitAt(rnd.nextInt(chars.length))));
  }

  // MODIFIED: This method now fetches appSettings and passes it to the service.
  Future<void> _submitInstallation() async {
    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 appSettings list to the submit method.
    final result = await service.submitInstallation(_installationData, appSettings);

    setState(() => _isLoading = false);

    if (!mounted) return;

    final message = result['message'] ?? 'An unknown error occurred.';
    final color = (result['status'] == 'S1' || result['status'] == 'S2')
        ? Colors.green
        : (result['status'] == 'L2_PENDING_IMAGES' ? Colors.orange : Colors.red);

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Air Sampling Installation'),
      ),
      body: AirManualInstallationWidget(
        data: _installationData,
        onSubmit: _submitInstallation,
        isLoading: _isLoading,
      ),
    );
  }
}