// lib/screens/river/manual/in_situ_sampling.dart

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:environment_monitoring_app/auth_provider.dart';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;

import '../../../models/river_in_situ_sampling_data.dart';
import '../../../services/river_in_situ_sampling_service.dart';
import '../../../services/local_storage_service.dart';
// --- ADDED: Import to get the active server configuration name ---
import '../../../services/server_config_service.dart';
// --- ADDED: Imports for zipping and retry queue logic ---
import '../../../services/zipping_service.dart';
import '../../../services/retry_service.dart';
import 'widgets/river_in_situ_step_1_sampling_info.dart';
import 'widgets/river_in_situ_step_2_site_info.dart';
import 'widgets/river_in_situ_step_3_data_capture.dart';
import 'widgets/river_in_situ_step_4_additional_info.dart';
import 'widgets/river_in_situ_step_5_summary.dart';


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

  @override
  State<RiverInSituSamplingScreen> createState() => _RiverInSituSamplingScreenState();
}

class _RiverInSituSamplingScreenState extends State<RiverInSituSamplingScreen> {
  final PageController _pageController = PageController();

  late RiverInSituSamplingData _data;

  final LocalStorageService _localStorageService = LocalStorageService();
  final ServerConfigService _serverConfigService = ServerConfigService();
  final ZippingService _zippingService = ZippingService();
  final RetryService _retryService = RetryService();

  int _currentPage = 0;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _data = RiverInSituSamplingData(
      samplingDate: DateFormat('yyyy-MM-dd').format(DateTime.now()),
      samplingTime: DateFormat('HH:mm:ss').format(DateTime.now()),
    );
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  void _nextPage() {
    if (_currentPage < 4) {
      _pageController.nextPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  void _previousPage() {
    if (_currentPage > 0) {
      _pageController.previousPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  Future<void> _submitForm() async {
    setState(() => _isLoading = true);

    final samplingService = Provider.of<RiverInSituSamplingService>(context, listen: false);
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final appSettings = authProvider.appSettings;

    // --- START: MODIFIED SUBMISSION LOGIC ---
    // The service call is updated to the new signature (no context).
    // The service now handles all local saving, so the manual save call is removed.
    final result = await samplingService.submitData(
      data: _data,
      appSettings: appSettings,
      authProvider: authProvider,
    );

    if (!mounted) return;

    setState(() => _isLoading = false);

    final message = result['message'] ?? 'An unknown error occurred.';
    final highLevelStatus = result['status'] as String? ?? 'L1';
    final bool isSuccess = highLevelStatus.startsWith('S') || highLevelStatus.startsWith('L4') || highLevelStatus == 'Queued';
    final color = isSuccess ? Colors.green : Colors.red;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: color, duration: const Duration(seconds: 4)),
    );

    Navigator.of(context).popUntil((route) => route.isFirst);
    // --- END: MODIFIED SUBMISSION LOGIC ---
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('In-Situ Sampling (${_currentPage + 1}/5)'),
        leading: _currentPage > 0
            ? IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: _previousPage,
        )
            : null,
      ),
      body: PageView(
        controller: _pageController,
        physics: const NeverScrollableScrollPhysics(),
        onPageChanged: (page) {
          setState(() {
            _currentPage = page;
          });
        },
        children: [
          RiverInSituStep1SamplingInfo(data: _data, onNext: _nextPage),
          RiverInSituStep2SiteInfo(data: _data, onNext: _nextPage),
          RiverInSituStep3DataCapture(data: _data, onNext: _nextPage),
          RiverInSituStep4AdditionalInfo(data: _data, onNext: _nextPage),
          RiverInSituStep5Summary(data: _data, onSubmit: _submitForm, isLoading: _isLoading),
        ],
      ),
    );
  }
}