// lib/screens/river/manual/widgets/river_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_in_situ_sampling_data.dart';
import '../../../../services/river_in_situ_sampling_service.dart';

class RiverInSituStep4AdditionalInfo extends StatefulWidget {
  final RiverInSituSamplingData data;
  final VoidCallback onNext;

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

  @override
  State<RiverInSituStep4AdditionalInfo> createState() =>
      _RiverInSituStep4AdditionalInfoState();
}

class _RiverInSituStep4AdditionalInfoState
    extends State<RiverInSituStep4AdditionalInfo> {
  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<RiverInSituSamplingService>(context, listen: false);

    // ✅ FIX: Get the station code directly from the data model.
    final String? stationCode = widget.data.selectedStation?['sampling_station_code'];

    // ✅ FIX: Pass the stationCode directly to the processing method.
    final file = await service.pickAndProcessImage(
      source,
      data: widget.data,
      imageInfo: imageInfo,
      isRequired: isRequired,
      stationCode: stationCode, // Pass the station code here
    );

    // FIX: Check if widget is still mounted after the await call to prevent defunct exception
    if (!mounted) return;

    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() {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();

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

      widget.data.optionalRemark1 = _optionalRemark1Controller.text;
      widget.data.optionalRemark2 = _optionalRemark2Controller.text;
      widget.data.optionalRemark3 = _optionalRemark3Controller.text;
      widget.data.optionalRemark4 = _optionalRemark4Controller.text;
      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,
      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),

          const SizedBox(height: 32),
          ElevatedButton(
            onPressed: _goToNextStep,
            style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16)),
            child: const Text('Next'),
          ),
        ],
      ),
    );
  }

  Widget _buildImagePicker(String title, String imageInfo, File? imageFile, Function(File?) setImageCallback, {TextEditingController? remarkController, bool isRequired = false}) {
    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: [
                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")),
              ],
            ),
          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(),
                ),
              ),
            ),
        ],
      ),
    );
  }
}