// lib/screens/river/investigative/manual_sampling/river_inves_in_situ_step_4_additional_info.dart

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

import '../../../../models/river_inves_manual_sampling_data.dart'; // Updated model
import '../../../../services/river_investigative_sampling_service.dart'; // Updated service

class RiverInvesStep4AdditionalInfo extends StatefulWidget {
  final RiverInvesManualSamplingData data;
  final VoidCallback onNext;

  const RiverInvesStep4AdditionalInfo({
    super.key,
    required this.data,
    required this.onNext,
  });

  @override
  State<RiverInvesStep4AdditionalInfo> createState() =>
      _RiverInvesStep4AdditionalInfoState();
}

class _RiverInvesStep4AdditionalInfoState
    extends State<RiverInvesStep4AdditionalInfo> {
  final _formKey = GlobalKey<FormState>();
  bool _isPickingImage = false;

  late final TextEditingController _optionalRemark1Controller;
  late final TextEditingController _optionalRemark2Controller;
  late final TextEditingController _optionalRemark3Controller;
  late final TextEditingController _optionalRemark4Controller;

  @override
  void initState() {
    super.initState();
    _optionalRemark1Controller = TextEditingController(text: widget.data.optionalRemark1);
    _optionalRemark2Controller = TextEditingController(text: widget.data.optionalRemark2);
    _optionalRemark3Controller = TextEditingController(text: widget.data.optionalRemark3);
    _optionalRemark4Controller = TextEditingController(text: widget.data.optionalRemark4);
  }

  @override
  void dispose() {
    _optionalRemark1Controller.dispose();
    _optionalRemark2Controller.dispose();
    _optionalRemark3Controller.dispose();
    _optionalRemark4Controller.dispose();
    super.dispose();
  }

  void _setImage(Function(File?) setImageCallback, ImageSource source,
      String imageInfo, {required bool isRequired}) async {
    if (_isPickingImage) return;
    setState(() => _isPickingImage = true);

    final service = Provider.of<RiverInvestigativeSamplingService>(context, listen: false);

    // --- MODIFICATION: Get station code based on selection ---
    final String? stationCode = widget.data.getDeterminedStationCode();
    // --- END MODIFICATION ---

    final file = await service.pickAndProcessImage( // Call the service's method
      source,
      data: widget.data, // Pass investigative data
      imageInfo: imageInfo,
      isRequired: isRequired,
      stationCode: stationCode, // Pass determined code
    );

    if (file != null) {
      setState(() => setImageCallback(file));
    } else if (mounted) {
      // ✅ CHANGE: Reverted. All photos (required and optional) must be landscape.
      _showSnackBar(
          'Image selection failed. Please ensure all photos are taken in landscape mode.',
          isError: true);
    }

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

  void _goToNextStep() {
    // Save remarks explicitly before validating/proceeding
    widget.data.optionalRemark1 = _optionalRemark1Controller.text.trim();
    widget.data.optionalRemark2 = _optionalRemark2Controller.text.trim();
    widget.data.optionalRemark3 = _optionalRemark3Controller.text.trim();
    widget.data.optionalRemark4 = _optionalRemark4Controller.text.trim();

    if (_formKey.currentState!.validate()) { // Validation (if any) is done here
      _formKey.currentState!.save(); // Save form fields (if any)

      if (widget.data.sampleTurbidityImage == null) {
        _showSnackBar(
            'Please attach the Sample Turbidity photo before proceeding.',
            isError: true);
        return;
      }
      widget.onNext();
    }
  }

  void _showSnackBar(String message, {bool isError = false}) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : null,
      ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey, // Needed if you add any validating FormFields later
      child: ListView(
        padding: const EdgeInsets.all(24.0),
        children: [
          Text("Additional Photos",
              style: Theme.of(context).textTheme.headlineSmall),
          const SizedBox(height: 24),
          Text("Required Photo *",
              style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 8),
          _buildImagePicker(
              'Sample Turbidity',
              'SAMPLE_TURBIDITY',
              widget.data.sampleTurbidityImage,
                  (file) => widget.data.sampleTurbidityImage = file,
              isRequired: true),
          const Divider(height: 32),
          Text("Optional Photos & Remarks",
              style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 8),
          _buildImagePicker('Optional Photo 1', 'OPTIONAL_1',
              widget.data.optionalImage1, (file) => widget.data.optionalImage1 = file,
              remarkController: _optionalRemark1Controller, isRequired: false),
          _buildImagePicker('Optional Photo 2', 'OPTIONAL_2',
              widget.data.optionalImage2, (file) => widget.data.optionalImage2 = file,
              remarkController: _optionalRemark2Controller, isRequired: false),
          _buildImagePicker('Optional Photo 3', 'OPTIONAL_3',
              widget.data.optionalImage3, (file) => widget.data.optionalImage3 = file,
              remarkController: _optionalRemark3Controller, isRequired: false),
          _buildImagePicker('Optional Photo 4', 'OPTIONAL_4',
              widget.data.optionalImage4, (file) => widget.data.optionalImage4 = file,
              remarkController: _optionalRemark4Controller, isRequired: false),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: _goToNextStep,
            style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16)),
            child: const Text('Next'),
          ),
        ],
      ),
    );
  }

  // _buildImagePicker remains the same as in RiverInSituStep4AdditionalInfo
  Widget _buildImagePicker(String title, String imageInfo, File? imageFile, Function(File?) setImageCallback, {TextEditingController? remarkController, bool isRequired = false}) {
    // Copied from RiverInSituStep4AdditionalInfoState._buildImagePicker
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(title + (isRequired ? ' *' : ''), style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
          const SizedBox(height: 8),
          if (imageFile != null)
            Stack(
              alignment: Alignment.topRight,
              children: [
                ClipRRect(borderRadius: BorderRadius.circular(8.0), child: Image.file(imageFile, key: UniqueKey(), height: 150, width: double.infinity, fit: BoxFit.cover)),
                Container(
                  margin: const EdgeInsets.all(4),
                  decoration: BoxDecoration(color: Colors.black.withOpacity(0.6), shape: BoxShape.circle),
                  child: IconButton(
                    visualDensity: VisualDensity.compact,
                    icon: const Icon(Icons.close, color: Colors.white, size: 20),
                    onPressed: () {
                      remarkController?.clear();
                      setState(() => setImageCallback(null));
                    },
                  ),
                ),
              ],
            )
          else
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                // Use the _setImage method defined in this state class
                ElevatedButton.icon(onPressed: _isPickingImage ? null : () => _setImage(setImageCallback, ImageSource.camera, imageInfo, isRequired: isRequired), icon: const Icon(Icons.camera_alt), label: const Text("Camera")),
                ElevatedButton.icon(onPressed: _isPickingImage ? null : () => _setImage(setImageCallback, ImageSource.gallery, imageInfo, isRequired: isRequired), icon: const Icon(Icons.photo_library), label: const Text("Gallery")),
              ],
            ),
          // Remarks field, linked via the passed controller
          if (remarkController != null && imageFile != null)
            Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: TextFormField(
                controller: remarkController,
                decoration: InputDecoration(
                  labelText: 'Remarks for $title',
                  hintText: 'Add an optional remark...',
                  border: const OutlineInputBorder(),
                ),
                // No validator needed for optional remarks
                // onSaved handled externally by _goToNextStep reading controllers
              ),
            ),
        ],
      ),
    );
  }
}