import 'package:flutter/material.dart';
import 'package:intl/intl.dart'; // ADDED: Import for date formatting
import 'package:provider/provider.dart';

import '../../../models/in_situ_sampling_data.dart';
import '../../../services/in_situ_sampling_service.dart';
import '../../../services/local_storage_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';

/// The main screen for the In-Situ Sampling feature.
/// This stateful widget orchestrates the multi-step process using a PageView.
/// It manages the overall data model and the service layer for the entire workflow.
class MarineInSituSampling extends StatefulWidget {
  const MarineInSituSampling({super.key});

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

class _MarineInSituSamplingState extends State<MarineInSituSampling> {
  final PageController _pageController = PageController();

  // REPAIRED: Changed from `final` to `late` to allow re-initialization.
  late InSituSamplingData _data;

  // A single instance of the service to be used by all child widgets.
  final InSituSamplingService _samplingService = InSituSamplingService();

  // Service for saving submission logs locally.
  final LocalStorageService _localStorageService = LocalStorageService();

  int _currentPage = 0;
  bool _isLoading = false;

  // ADDED: initState to create a fresh data object each time the widget is created.
  @override
  void initState() {
    super.initState();
    // This is the core of the fix. It creates a NEW data object with the
    // CURRENT date and time every time the user starts a new sampling.
    _data = InSituSamplingData(
      samplingDate: DateFormat('yyyy-MM-dd').format(DateTime.now()),
      samplingTime: DateFormat('HH:mm:ss').format(DateTime.now()),
    );
  }

  @override
  void dispose() {
    _pageController.dispose();
    // Dispose the service to clean up its resources (e.g., stream controllers).
    _samplingService.dispose();
    super.dispose();
  }

  /// Navigates to the next page in the form.
  void _nextPage() {
    if (_currentPage < 3) {
      _pageController.nextPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  /// Navigates to the previous page in the form.
  void _previousPage() {
    if (_currentPage > 0) {
      _pageController.previousPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  /// Handles the final submission process.
  Future<void> _submitForm() async {
    setState(() => _isLoading = true);

    // Use the service to submit the data.
    final result = await _samplingService.submitData(_data);

    if (!mounted) return;

    // Update the data model with the submission result.
    _data.submissionStatus = result['status'];
    _data.submissionMessage = result['message'];
    _data.reportId = result['reportId']?.toString();

    // Save a log of the submission locally.
    await _localStorageService.saveInSituSamplingData(_data);

    setState(() => _isLoading = false);

    // Show feedback to the user based on the result.
    final message = result['message'] ?? 'An unknown error occurred.';
    final color = (result['status'] == 'L3')
        ? Colors.green
        : (result['status'] == 'L2' ? Colors.orange : Colors.red);

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

    // If submission was fully successful, navigate back to the home screen.
    if (result['status'] == 'L3') {
      Navigator.of(context).popUntil((route) => route.isFirst);
    }
  }

  @override
  Widget build(BuildContext context) {
    // Use Provider.value to provide the existing service instance to all child widgets.
    return Provider.value(
      value: _samplingService,
      child: Scaffold(
        appBar: AppBar(
          title: Text('In-Situ Sampling (${_currentPage + 1}/4)'),
          // Show a back button on all pages except the first one.
          leading: _currentPage > 0
              ? IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: _previousPage,
          )
              : null,
        ),
        body: PageView(
          controller: _pageController,
          // Disable manual swiping between pages.
          physics: const NeverScrollableScrollPhysics(),
          onPageChanged: (page) {
            setState(() {
              _currentPage = page;
            });
          },
          children: [
            // Each step is a separate widget, receiving the data model and navigation callbacks.
            InSituStep1SamplingInfo(data: _data, onNext: _nextPage),
            InSituStep2SiteInfo(data: _data, onNext: _nextPage),
            InSituStep3DataCapture(data: _data, onNext: _nextPage),
            InSituStep4Summary(data: _data, onSubmit: _submitForm, isLoading: _isLoading),
          ],
        ),
      ),
    );
  }
}