// lib/screens/river/investigative/river_investigative_manual_sampling.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart'; // For formatting date/time

import '../../../../auth_provider.dart';
import '../../../../models/river_inves_manual_sampling_data.dart'; // Updated model
import '../../../../services/river_investigative_sampling_service.dart'; // Updated service
// Removed CustomStepper import

// Import Step Widgets
import 'manual_sampling/river_inves_in_situ_step_1_sampling_info.dart';
import 'manual_sampling/river_inves_in_situ_step_2_site_info.dart';
import 'manual_sampling/river_inves_in_situ_step_3_data_capture.dart';
import 'manual_sampling/river_inves_in_situ_step_4_additional_info.dart';
import 'manual_sampling/river_inves_in_situ_step_5_summary.dart';

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

  @override
  State<RiverInvestigativeManualSamplingScreen> createState() =>
      _RiverInvestigativeManualSamplingScreenState();
}

class _RiverInvestigativeManualSamplingScreenState
    extends State<RiverInvestigativeManualSamplingScreen> {
  int _currentStep = 0;
  bool _isLoading = false;
  late RiverInvesManualSamplingData _samplingData;

  @override
  void initState() {
    super.initState();
    _samplingData = RiverInvesManualSamplingData(
      // Initialize with current date and time if needed, handled in Step 1 init
    );
  }

  void _nextStep() {
    if (_currentStep < 4) {
      setState(() {
        _currentStep++;
      });
    } else {
      _submitForm();
    }
  }

  void _previousStep() {
    if (_currentStep > 0) {
      setState(() {
        _currentStep--;
      });
    } else {
      Navigator.of(context).pop();
    }
  }

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

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

    try {
      final result = await service.submitData(
        data: _samplingData,
        appSettings: auth.appSettings,
        authProvider: auth,
        // logDirectory: null, // Let service handle initial log creation
      );

      _samplingData.submissionStatus = result['status'];
      _samplingData.submissionMessage = result['message'];
      _samplingData.reportId = result['reportId'];

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(result['message'] ?? 'Submission processed.'),
            backgroundColor: result['success'] ? Colors.green : Colors.orange,
          ),
        );
        if (result['success']) {
          Future.delayed(const Duration(seconds: 2), () {
            if (mounted) {
              Navigator.of(context).pop();
            }
          });
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('An unexpected error occurred: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
      _samplingData.submissionStatus = 'Error';
      _samplingData.submissionMessage = 'An unexpected error occurred: $e';
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  // --- MODIFICATION: Removed _getStepTitle method ---

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_isLoading) return false;
        if (_currentStep > 0) {
          final shouldPop = await showDialog<bool>(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text('Discard Sampling Data?'),
              content: const Text('Are you sure you want to go back? All unsaved data for this sampling event will be lost.'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: const Text('Cancel'),
                ),
                TextButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  child: const Text('Discard'),
                ),
              ],
            ),
          );
          return shouldPop ?? false;
        }
        return true;
      },
      child: Scaffold(
        appBar: AppBar(
          // --- MODIFICATION: Title is now dynamic to match river manual ---
          title: Text('In-Situ Sampling (${_currentStep + 1}/5)'),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: _isLoading ? null : _previousStep,
          ),
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(4.0),
            child: _isLoading ? const LinearProgressIndicator() : const SizedBox.shrink(),
          ),
        ),
        // --- MODIFICATION: Body is now the IndexedStack directly ---
        body: IndexedStack(
          index: _currentStep,
          children: <Widget>[
            RiverInvesStep1SamplingInfo(
              data: _samplingData,
              onNext: _nextStep,
            ),
            RiverInvesStep2SiteInfo(
              data: _samplingData,
              onNext: _nextStep,
            ),
            RiverInvesStep3DataCapture(
              data: _samplingData,
              onNext: _nextStep,
            ),
            RiverInvesStep4AdditionalInfo(
              data: _samplingData,
              onNext: _nextStep,
            ),
            RiverInvesStep5Summary(
              data: _samplingData,
              onSubmit: _submitForm,
              isLoading: _isLoading,
            ),
          ],
        ),
        // --- END MODIFICATION ---
      ),
    );
  }
}