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

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

import '../../../models/river_in_situ_sampling_data.dart';
import '../../../services/river_in_situ_sampling_service.dart';
import '../../../services/local_storage_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 RiverInSituSamplingService _samplingService = RiverInSituSamplingService();
  final LocalStorageService _localStorageService = LocalStorageService();

  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();
    _samplingService.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 result = await _samplingService.submitData(_data);

    if (!mounted) return;

    _data.submissionStatus = result['status'];
    _data.submissionMessage = result['message'];
    _data.reportId = result['reportId']?.toString();

    await _localStorageService.saveRiverInSituSamplingData(_data);

    setState(() => _isLoading = false);

    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)),
    );

    // ✅ CORRECTED: The navigation now happens regardless of the submission status.
    // This ensures the form closes even after a failed (offline) submission.
    Navigator.of(context).popUntil((route) => route.isFirst);
  }

  @override
  Widget build(BuildContext context) {
    return Provider.value(
      value: _samplingService,
      child: 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),
          ],
        ),
      ),
    );
  }
}