// lib/main.dart

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

// CHANGED: Added imports for MultiProvider and the services to be provided.
import 'package:provider/single_child_widget.dart';
import 'package:environment_monitoring_app/services/local_storage_service.dart';
import 'package:environment_monitoring_app/services/river_in_situ_sampling_service.dart';
// --- ADDED: Import for the new AirSamplingService ---
import 'package:environment_monitoring_app/services/air_sampling_service.dart';
import 'package:environment_monitoring_app/services/telegram_service.dart';

import 'package:environment_monitoring_app/theme.dart';
import 'package:environment_monitoring_app/auth_provider.dart';

// Core Screens
import 'package:environment_monitoring_app/screens/login.dart';
import 'package:environment_monitoring_app/screens/register.dart';
import 'package:environment_monitoring_app/screens/forgot_password.dart';
import 'package:environment_monitoring_app/screens/logout.dart';
import 'package:environment_monitoring_app/home_page.dart';
import 'package:environment_monitoring_app/screens/profile.dart';
import 'package:environment_monitoring_app/screens/settings.dart';

// Department Home Pages
import 'package:environment_monitoring_app/screens/air/air_home_page.dart';
import 'package:environment_monitoring_app/screens/river/river_home_page.dart';
import 'package:environment_monitoring_app/screens/marine/marine_home_page.dart';

// Air Screens
import 'package:environment_monitoring_app/screens/air/manual/air_manual_dashboard.dart';
// --- UPDATED: Imports now point to the new separate screens ---
import 'package:environment_monitoring_app/screens/air/manual/air_manual_installation_screen.dart';
import 'package:environment_monitoring_app/screens/air/manual/air_manual_collection_screen.dart';
import 'package:environment_monitoring_app/screens/air/manual/report.dart' as airManualReport;
import 'package:environment_monitoring_app/screens/air/manual/data_status_log.dart' as airManualDataStatusLog;
import 'package:environment_monitoring_app/screens/air/manual/image_request.dart' as airManualImageRequest;
import 'package:environment_monitoring_app/screens/air/continuous/air_continuous_dashboard.dart';
import 'package:environment_monitoring_app/screens/air/continuous/overview.dart' as airContinuousOverview;
import 'package:environment_monitoring_app/screens/air/continuous/entry.dart' as airContinuousEntry;
import 'package:environment_monitoring_app/screens/air/continuous/report.dart' as airContinuousReport;
import 'package:environment_monitoring_app/screens/air/investigative/air_investigative_dashboard.dart';
import 'package:environment_monitoring_app/screens/air/investigative/overview.dart' as airInvestigativeOverview;
import 'package:environment_monitoring_app/screens/air/investigative/entry.dart' as airInvestigativeEntry;
import 'package:environment_monitoring_app/screens/air/investigative/report.dart' as airInvestigativeReport;

// River Screens
import 'package:environment_monitoring_app/screens/river/manual/river_manual_dashboard.dart';
// NOTE: This import points to the main stepper screen for the River In-Situ workflow.
import 'package:environment_monitoring_app/screens/river/manual/in_situ_sampling.dart' as riverManualInSituSampling;
import 'package:environment_monitoring_app/screens/river/manual/data_status_log.dart' as riverManualDataStatusLog;

//import 'package:environment_monitoring_app/screens/river/manual/in_situ_sampling.dart' as riverManualInSituSampling;
import 'package:environment_monitoring_app/screens/river/manual/report.dart' as riverManualReport;
import 'package:environment_monitoring_app/screens/river/manual/triennial_sampling.dart' as riverManualTriennialSampling;
//import 'package:environment_monitoring_app/screens/river/manual/data_status_log.dart' as riverManualDataStatusLog;
import 'package:environment_monitoring_app/screens/river/manual/image_request.dart' as riverManualImageRequest;
import 'package:environment_monitoring_app/screens/river/continuous/river_continuous_dashboard.dart';
import 'package:environment_monitoring_app/screens/river/continuous/overview.dart' as riverContinuousOverview;
import 'package:environment_monitoring_app/screens/river/continuous/entry.dart' as riverContinuousEntry;
import 'package:environment_monitoring_app/screens/river/continuous/report.dart' as riverContinuousReport;
import 'package:environment_monitoring_app/screens/river/investigative/river_investigative_dashboard.dart';
import 'package:environment_monitoring_app/screens/river/investigative/overview.dart' as riverInvestigativeOverview;
import 'package:environment_monitoring_app/screens/river/investigative/entry.dart' as riverInvestigativeEntry;
import 'package:environment_monitoring_app/screens/river/investigative/report.dart' as riverInvestigativeReport;

// Marine Screens
import 'package:environment_monitoring_app/screens/marine/manual/marine_manual_dashboard.dart';
import 'package:environment_monitoring_app/screens/marine/manual/info_centre_document.dart' as marineManualInfoCentreDocument;
import 'package:environment_monitoring_app/screens/marine/manual/pre_sampling.dart' as marineManualPreSampling;
import 'package:environment_monitoring_app/screens/marine/manual/in_situ_sampling.dart' as marineManualInSituSampling;
import 'package:environment_monitoring_app/screens/marine/manual/report.dart' as marineManualReport;
import 'package:environment_monitoring_app/screens/marine/manual/data_status_log.dart' as marineManualDataStatusLog;
import 'package:environment_monitoring_app/screens/marine/manual/image_request.dart' as marineManualImageRequest;
import 'package:environment_monitoring_app/screens/marine/continuous/marine_continuous_dashboard.dart';
import 'package:environment_monitoring_app/screens/marine/continuous/overview.dart' as marineContinuousOverview;
import 'package:environment_monitoring_app/screens/marine/continuous/entry.dart' as marineContinuousEntry;
import 'package:environment_monitoring_app/screens/marine/continuous/report.dart' as marineContinuousReport;
import 'package:environment_monitoring_app/screens/marine/investigative/marine_investigative_dashboard.dart';
import 'package:environment_monitoring_app/screens/marine/investigative/overview.dart' as marineInvestigativeOverview;
import 'package:environment_monitoring_app/screens/marine/investigative/entry.dart' as marineInvestigativeEntry;
import 'package:environment_monitoring_app/screens/marine/investigative/report.dart' as marineInvestigativeReport;

import 'package:environment_monitoring_app/models/tarball_data.dart';
import 'package:environment_monitoring_app/screens/marine/manual/tarball_sampling_step1.dart';
import 'package:environment_monitoring_app/screens/marine/manual/tarball_sampling_step2.dart';
import 'package:environment_monitoring_app/screens/marine/manual/tarball_sampling_step3_summary.dart';


void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  setupServices();

  runApp(
    // CHANGED: Converted to MultiProvider to support all necessary services.
    MultiProvider(
      providers: <SingleChildWidget>[
        // The original AuthProvider
        ChangeNotifierProvider(create: (_) => AuthProvider()),
        // Provider for Local Storage Service
        Provider(create: (_) => LocalStorageService()),
        // Provider for the River In-Situ Sampling Service
        Provider(create: (_) => RiverInSituSamplingService()),
        // --- ADDED: Provider for the new AirSamplingService ---
        Provider(create: (_) => AirSamplingService()),
      ],
      child: const RootApp(),
    ),
  );
}

void setupServices() {
  final telegramService = TelegramService();

  Future.delayed(const Duration(seconds: 5), () {
    debugPrint("[Main] Performing initial alert queue processing on app start.");
    telegramService.processAlertQueue();
  });

  Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> results) {
    if (results.contains(ConnectivityResult.mobile) || results.contains(ConnectivityResult.wifi)) {
      debugPrint("[Main] Internet connection detected. Triggering alert queue processing.");
      telegramService.processAlertQueue();
    } else {
      debugPrint("[Main] Internet connection lost.");
    }
  });
}

class RootApp extends StatelessWidget {
  const RootApp({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<AuthProvider>(
      builder: (context, auth, child) {
        Widget homeWidget;
        if (auth.isLoading) {
          homeWidget = const SplashScreen();
        } else if (auth.isLoggedIn) {
          homeWidget = const HomePage();
        } else {
          homeWidget = const LoginScreen();
        }

        return MaterialApp(
          title: 'Environment Monitoring App',
          theme: AppTheme.darkBlueTheme,
          debugShowCheckedModeBanner: false,
          home: homeWidget,

          onGenerateRoute: (settings) {
            if (settings.name == '/marine/manual/tarball/step2') {
              final args = settings.arguments as TarballSamplingData;
              return MaterialPageRoute(builder: (context) {
                return TarballSamplingStep2(data: args);
              });
            }
            if (settings.name == '/marine/manual/tarball/step3') {
              final args = settings.arguments as TarballSamplingData;
              return MaterialPageRoute(builder: (context) {
                return TarballSamplingStep3Summary(data: args);
              });
            }
            // NOTE: The River and Air In-Situ forms use an internal stepper,
            // so they do not require onGenerateRoute logic for their steps.
            return null;
          },
          routes: {
            // Auth Routes
            '/register': (context) => const RegisterScreen(),
            '/forgot-password': (context) => ForgotPasswordScreen(),
            '/logout': (context) => const LogoutScreen(),
            '/home': (context) => const HomePage(),
            '/profile': (context) => const ProfileScreen(),
            '/settings': (context) => const SettingsScreen(),

            // Department Home Pages
            '/air/home': (context) => const AirHomePage(),
            '/river/home': (context) => const RiverHomePage(),
            '/marine/home': (context) => const MarineHomePage(),

            // Air Manual
            '/air/manual/dashboard': (context) => AirManualDashboard(),
            // --- UPDATED: Routes now point to the new separate screens ---
            '/air/manual/installation': (context) => const AirManualInstallationScreen(),
            '/air/manual/collection': (context) => const AirManualCollectionScreen(),
            '/air/manual/report': (context) => airManualReport.AirManualReport(),
            '/air/manual/data-log': (context) => airManualDataStatusLog.AirManualDataStatusLog(),
            '/air/manual/image-request': (context) => airManualImageRequest.AirManualImageRequest(),

            // Air Continuous
            '/air/continuous/dashboard': (context) => AirContinuousDashboard(),
            '/air/continuous/overview': (context) => airContinuousOverview.OverviewScreen(),
            '/air/continuous/entry': (context) => airContinuousEntry.EntryScreen(),
            '/air/continuous/report': (context) => airContinuousReport.ReportScreen(),

            // Air Investigative
            '/air/investigative/dashboard': (context) => AirInvestigativeDashboard(),
            '/air/investigative/overview': (context) => airInvestigativeOverview.OverviewScreen(),
            '/air/investigative/entry': (context) => airInvestigativeEntry.EntryScreen(),
            '/air/investigative/report': (context) => airInvestigativeReport.ReportScreen(),

            // River Manual
            '/river/manual/dashboard': (context) => RiverManualDashboard(),
            '/river/manual/in-situ': (context) => riverManualInSituSampling.RiverInSituSamplingScreen(),

            //'/river/manual/in-situ': (context) => riverManualInSituSampling.RiverInSituSampling(),
            '/river/manual/report': (context) => riverManualReport.RiverManualReport(),
            '/river/manual/triennial': (context) => riverManualTriennialSampling.RiverTriennialSampling(),
            '/river/manual/data-log': (context) => riverManualDataStatusLog.RiverDataStatusLog(),
            //'/river/manual/data-log': (context) => riverManualDataStatusLog.RiverManualDataStatusLog(),
            '/river/manual/image-request': (context) => riverManualImageRequest.RiverManualImageRequest(),

            // River Continuous
            '/river/continuous/dashboard': (context) => RiverContinuousDashboard(),
            '/river/continuous/overview': (context) => riverContinuousOverview.OverviewScreen(),
            '/river/continuous/entry': (context) => riverContinuousEntry.EntryScreen(),
            '/river/continuous/report': (context) => riverContinuousReport.ReportScreen(),

            // River Investigative
            '/river/investigative/dashboard': (context) => RiverInvestigativeDashboard(),
            '/river/investigative/overview': (context) => riverInvestigativeOverview.OverviewScreen(),
            '/river/investigative/entry': (context) => riverInvestigativeEntry.EntryScreen(),
            '/river/investigative/report': (context) => riverInvestigativeReport.ReportScreen(),

            // Marine Manual
            '/marine/manual/dashboard': (context) => MarineManualDashboard(),
            '/marine/manual/info': (context) => marineManualInfoCentreDocument.MarineInfoCentreDocument(),
            '/marine/manual/pre-sampling': (context) => marineManualPreSampling.MarinePreSampling(),
            '/marine/manual/in-situ': (context) => marineManualInSituSampling.MarineInSituSampling(),
            '/marine/manual/tarball': (context) => const TarballSamplingStep1(),
            '/marine/manual/report': (context) => marineManualReport.MarineManualReport(),
            '/marine/manual/data-log': (context) => marineManualDataStatusLog.MarineManualDataStatusLog(),
            '/marine/manual/image-request': (context) => marineManualImageRequest.MarineManualImageRequest(),

            // Marine Continuous
            '/marine/continuous/dashboard': (context) => MarineContinuousDashboard(),
            '/marine/continuous/overview': (context) => marineContinuousOverview.OverviewScreen(),
            '/marine/continuous/entry': (context) => marineContinuousEntry.EntryScreen(),
            '/marine/continuous/report': (context) => marineContinuousReport.ReportScreen(),

            // Marine Investigative
            '/marine/investigative/dashboard': (context) => MarineInvestigativeDashboard(),
            '/marine/investigative/overview': (context) => marineInvestigativeOverview.OverviewScreen(),
            '/marine/investigative/entry': (context) => marineInvestigativeEntry.EntryScreen(),
            '/marine/investigative/report': (context) => marineInvestigativeReport.ReportScreen(),
          },
        );
      },
    );
  }
}

class SplashScreen extends StatelessWidget {
  const SplashScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 20),
            Text('Loading app data...', style: TextStyle(fontSize: 16)),
          ],
        ),
      ),
    );
  }
}
