// lib/screens/marine/investigative/marine_investigative_manual_sampling.dart

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

import '../../../models/marine_inves_manual_sampling_data.dart';
import '../../../services/marine_investigative_sampling_service.dart';
import '../../../auth_provider.dart';

import 'manual_sampling/marine_inves_manual_step_1_sampling_info.dart';
import 'manual_sampling/marine_inves_manual_step_2_site_info.dart';
import 'manual_sampling/marine_inves_manual_step_3_data_capture.dart';
import 'manual_sampling/marine_inves_manual_step_4_summary.dart';

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

  @override
  State<MarineInvestigativeManualSampling> createState() => _MarineInvestigativeManualSamplingState();
}

class _MarineInvestigativeManualSamplingState extends State<MarineInvestigativeManualSampling> {
  final PageController _pageController = PageController();
  final MarineInvesManualSamplingData _data = MarineInvesManualSamplingData();
  int _currentStep = 0;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    // Pre-fill sampling date and time when the form is first created
    final now = DateTime.now();
    _data.samplingDate = "${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}";
    _data.samplingTime = "${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}";
  }

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

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

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

  Future<Map<String, dynamic>> _submitData() async {
    setState(() => _isLoading = true);

    final service = context.read<MarineInvestigativeSamplingService>();
    final authProvider = context.read<AuthProvider>();
    final appSettings = authProvider.appSettings;

    try {
      final result = await service.submitInvestigativeSample(
        data: _data,
        appSettings: appSettings,
        authProvider: authProvider,
        context: context,
      );

      return result;

    } catch (e) {
      return {'success': false, 'message': 'An unexpected error occurred: $e'};
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> pages = [
      MarineInvesManualStep1SamplingInfo(data: _data, onNext: _nextPage),
      MarineInvesManualStep2SiteInfo(data: _data, onNext: _nextPage),
      MarineInvesManualStep3DataCapture(data: _data, onNext: _nextPage),
      MarineInvesManualStep4Summary(
        data: _data,
        onSubmit: _submitData,
        isLoading: _isLoading,
      ),
    ];

    return Scaffold(
      appBar: AppBar(
        title: Text('Marine Investigative Sampling (Step ${_currentStep + 1} of 4)'),
        leading: _currentStep == 0
            ? IconButton(
          icon: const Icon(Icons.close),
          onPressed: () => Navigator.of(context).pop(),
        )
            : IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: _previousPage,
        ),
      ),
      body: PageView(
        controller: _pageController,
        physics: const NeverScrollableScrollPhysics(),
        onPageChanged: (index) {
          setState(() {
            _currentStep = index;
          });
        },
        children: pages,
      ),
    );
  }
}