// lib/screens/marine/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 '../../../models/in_situ_sampling_data.dart';
import '../../../services/marine_in_situ_sampling_service.dart';
import 'widgets/in_situ_step_1_sampling_info.dart';
import 'widgets/in_situ_step_2_site_info.dart';
import 'widgets/in_situ_step_3_data_capture.dart';
import 'widgets/in_situ_step_4_summary.dart';

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

  @override
  State<MarineInSituSampling> createState() => _MarineInSituSamplingState();
}

class _MarineInSituSamplingState extends State<MarineInSituSampling> {
  final PageController _pageController = PageController();
  late InSituSamplingData _data;
  late MarineInSituSamplingService _samplingService;

  int _currentPage = 0;
  bool _isLoading = false;

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

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _samplingService = Provider.of<MarineInSituSamplingService>(context);
  }

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

  void _nextPage() {
    if (_currentPage < 3) {
      _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,
      );
    }
  }

  /// This function contains the core logic for submitting data and returns the result.
  /// UI actions like SnackBars and navigation are handled by the caller (summary screen).
  Future<Map<String, dynamic>> _submitFormLogic() async {
    setState(() => _isLoading = true);

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

    final result = await _samplingService.submitInSituSample(
      data: _data,
      appSettings: appSettings,
      context: context,
      authProvider: authProvider,
    );

    if (mounted) {
      setState(() => _isLoading = false);
    }

    return result;
  }


  @override
  Widget build(BuildContext context) {
    return Provider<MarineInSituSamplingService>.value(
      value: _samplingService,
      child: Scaffold(
        appBar: AppBar(
          title: Text('In-Situ Sampling (${_currentPage + 1}/4)'),
          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: [
            InSituStep1SamplingInfo(data: _data, onNext: _nextPage),
            InSituStep2SiteInfo(data: _data, onNext: _nextPage),
            InSituStep3DataCapture(data: _data, onNext: _nextPage),
            InSituStep4Summary(data: _data, onSubmit: _submitFormLogic, isLoading: _isLoading),
          ],
        ),
      ),
    );
  }
}