// lib/screens/river/manual/triennial/river_manual_triennial_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/river_manual_triennial_sampling_data.dart';
import '../../../../services/river_manual_triennial_sampling_service.dart';
// --- ADDED: Missing imports for step widgets ---
import 'widgets/river_manual_triennial_step_1_sampling_info.dart';
import 'widgets/river_manual_triennial_step_2_site_info.dart';
import 'widgets/river_manual_triennial_step_3_data_capture.dart';
import 'widgets/river_manual_triennial_step_4_additional_info.dart';
import 'widgets/river_manual_triennial_step_5_summary.dart';

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

  @override
  State<RiverManualTriennialSamplingScreen> createState() => _RiverManualTriennialSamplingScreenState();
}

class _RiverManualTriennialSamplingScreenState extends State<RiverManualTriennialSamplingScreen> {
  final PageController _pageController = PageController();
  late RiverManualTriennialSamplingData _data;
  int _currentPage = 0;
  bool _isLoading = false;

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

  @override
  void dispose() {
    _pageController.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 samplingService = Provider.of<RiverManualTriennialSamplingService>(context, listen: false);
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final appSettings = authProvider.appSettings;

    final result = await samplingService.submitData(
        data: _data,
        appSettings: appSettings,
        authProvider: authProvider
    );

    if (!mounted) return;
    setState(() => _isLoading = false);

    final bool isSuccess = result['success'] ?? false;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(result['message'] ?? "An unknown error occurred."),
        backgroundColor: isSuccess ? Colors.green : Colors.red,
      ),
    );
    Navigator.of(context).popUntil((route) => route.isFirst);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Triennial 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: [
          RiverManualTriennialStep1SamplingInfo(data: _data, onNext: _nextPage),
          RiverManualTriennialStep2SiteInfo(data: _data, onNext: _nextPage),
          RiverManualTriennialStep3DataCapture(data: _data, onNext: _nextPage),
          RiverManualTriennialStep4AdditionalInfo(data: _data, onNext: _nextPage),
          RiverManualTriennialStep5Summary(data: _data, onSubmit: _submitForm, isLoading: _isLoading),
        ],
      ),
    );
  }
}