// lib/screens/marine/manual/widgets/in_situ_step_2_site_info.dart

import 'dart:io';
import 'dart:typed_data'; // <-- Required for Uint8List
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import '../../../../models/in_situ_sampling_data.dart';
import '../../../../services/marine_in_situ_sampling_service.dart';

/// The second step of the In-Situ Sampling form.
/// Gathers on-site conditions (weather, tide) and handles all photo attachments.
class InSituStep2SiteInfo extends StatefulWidget {
  final InSituSamplingData data;
  final VoidCallback onNext;

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

  @override
  State<InSituStep2SiteInfo> createState() => _InSituStep2SiteInfoState();
}

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

  late final TextEditingController _eventRemarksController;
  late final TextEditingController _labRemarksController;

  final List<String> _weatherOptions = ['Clear', 'Cloudy', 'Drizzle', 'Rainy', 'Windy'];
  final List<String> _tideOptions = ['High', 'Low'];
  final List<String> _seaConditionOptions = ['Calm', 'Moderate Wave', 'High Wave'];

  @override
  void initState() {
    super.initState();
    _eventRemarksController = TextEditingController(text: widget.data.eventRemarks);
    _labRemarksController = TextEditingController(text: widget.data.labRemarks);
  }

  @override
  void dispose() {
    _eventRemarksController.dispose();
    _labRemarksController.dispose();
    super.dispose();
  }

  /// Handles picking and processing an image using the dedicated service.
  void _setImage(Function(File?) setImageCallback, ImageSource source, String imageInfo, {required bool isRequired}) async {
    if (_isPickingImage) return;
    setState(() => _isPickingImage = true);

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

    // Always pass `isRequired: true` to the service to enforce landscape check
    // and watermarking for ALL photos (required or optional).
    final file = await service.pickAndProcessImage(source, data: widget.data, imageInfo: imageInfo, isRequired: true);

    if (file != null) {
      setState(() => setImageCallback(file));
    } else if (mounted) {
      _showSnackBar('Image selection failed. Please ensure all photos are taken in landscape (horizontal) mode.', isError: true);
    }

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

  /// Validates the form and all required images before proceeding.
  void _goToNextStep() {
    if (widget.data.leftLandViewImage == null ||
        widget.data.rightLandViewImage == null ||
        widget.data.waterFillingImage == null ||
        widget.data.seawaterColorImage == null) {
      _showSnackBar('Please attach all 4 required photos before proceeding.', isError: true);
      return;
    }

    if (!_formKey.currentState!.validate()) {
      return;
    }

    _formKey.currentState!.save();
    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) {
    final bool areAdditionalPhotosAttached = widget.data.phPaperImage != null ||
        widget.data.optionalImage1 != null ||
        widget.data.optionalImage2 != null ||
        widget.data.optionalImage3 != null ||
        widget.data.optionalImage4 != null;

    return Form(
      key: _formKey,
      child: ListView(
        padding: const EdgeInsets.all(24.0),
        children: [
          // --- Section: On-Site Information ---
          Text("On-Site Information", style: Theme.of(context).textTheme.headlineSmall),
          const SizedBox(height: 24),
          DropdownButtonFormField<String>(
            value: widget.data.weather,
            items: _weatherOptions.map((item) => DropdownMenuItem(value: item, child: Text(item))).toList(),
            onChanged: (value) => setState(() => widget.data.weather = value),
            decoration: const InputDecoration(labelText: 'Weather *'),
            validator: (value) => value == null ? 'Weather is required' : null,
          ),
          const SizedBox(height: 16),
          DropdownButtonFormField<String>(
            value: widget.data.tideLevel,
            items: _tideOptions.map((item) => DropdownMenuItem(value: item, child: Text(item))).toList(),
            onChanged: (value) => setState(() => widget.data.tideLevel = value),
            decoration: const InputDecoration(labelText: 'Tide Level *'),
            validator: (value) => value == null ? 'Tide level is required' : null,
          ),
          const SizedBox(height: 16),
          DropdownButtonFormField<String>(
            value: widget.data.seaCondition,
            items: _seaConditionOptions.map((item) => DropdownMenuItem(value: item, child: Text(item))).toList(),
            onChanged: (value) => setState(() => widget.data.seaCondition = value),
            decoration: const InputDecoration(labelText: 'Sea Condition *'),
            validator: (value) => value == null ? 'Sea condition is required' : null,
          ),
          const SizedBox(height: 24),

          // --- Section: Required Photos ---
          Text("Required Photos *", style: Theme.of(context).textTheme.titleLarge),
          const Text(
              "All photos must be in landscape (horizontal) orientation. A watermark will be applied automatically.",
              style: TextStyle(color: Colors.grey)
          ),
          const SizedBox(height: 8),
          _buildImagePicker('Left Side Land View', 'LEFT_LAND_VIEW', widget.data.leftLandViewImage, (file) => widget.data.leftLandViewImage = file, isRequired: true),
          _buildImagePicker('Right Side Land View', 'RIGHT_LAND_VIEW', widget.data.rightLandViewImage, (file) => widget.data.rightLandViewImage = file, isRequired: true),
          _buildImagePicker('Filling Water into Sample Bottle', 'WATER_FILLING', widget.data.waterFillingImage, (file) => widget.data.waterFillingImage = file, isRequired: true),
          _buildImagePicker('Seawater in Clear Glass Bottle', 'SEAWATER_COLOR', widget.data.seawaterColorImage, (file) => widget.data.seawaterColorImage = file, isRequired: true),
          const SizedBox(height: 24),

          // --- Section: Additional Photos & Remarks ---
          Text("Additional Photos & Remarks", style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 8),
          _buildImagePicker('Examine Preservative (pH paper)', 'PH_PAPER', widget.data.phPaperImage, (file) => widget.data.phPaperImage = file, isRequired: false),
          _buildImagePicker('Optional Photo 1', 'OPTIONAL_1', widget.data.optionalImage1, (file) => widget.data.optionalImage1 = file, isRequired: false),
          _buildImagePicker('Optional Photo 2', 'OPTIONAL_2', widget.data.optionalImage2, (file) => widget.data.optionalImage2 = file, isRequired: false),
          _buildImagePicker('Optional Photo 3', 'OPTIONAL_3', widget.data.optionalImage3, (file) => widget.data.optionalImage3 = file, isRequired: false),
          _buildImagePicker('Optional Photo 4', 'OPTIONAL_4', widget.data.optionalImage4, (file) => widget.data.optionalImage4 = file, isRequired: false),
          const SizedBox(height: 24),

          Text("Remarks", style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 16),
          TextFormField(
            controller: _eventRemarksController,
            decoration: InputDecoration(
                labelText: areAdditionalPhotosAttached ? 'Event Remarks *' : 'Event Remarks (Optional)',
                hintText: 'e.g., unusual smells, colors, etc.'
            ),
            onSaved: (value) => widget.data.eventRemarks = value,
            validator: (value) {
              if (areAdditionalPhotosAttached && (value == null || value.trim().isEmpty)) {
                return 'Event Remarks are required when attaching additional photos.';
              }
              return null;
            },
            maxLines: 3,
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _labRemarksController,
            decoration: const InputDecoration(labelText: 'Lab Remarks (Optional)'),
            onSaved: (value) => widget.data.labRemarks = value,
            maxLines: 3,
          ),
          const SizedBox(height: 32),
          ElevatedButton(
            onPressed: _goToNextStep,
            style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16)),
            child: const Text('Next'),
          ),
        ],
      ),
    );
  }

  /// A reusable widget for picking and displaying an image.
  Widget _buildImagePicker(String title, String imageInfo, File? imageFile, Function(File?) setImageCallback, {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: [
                // --- START MODIFICATION: Use FutureBuilder to load bytes async ---
                ClipRRect(
                  borderRadius: BorderRadius.circular(8.0),
                  child: FutureBuilder<Uint8List>(
                    // Use ValueKey to ensure FutureBuilder refetches when the file path changes
                    key: ValueKey(imageFile.path),
                    future: imageFile.readAsBytes(),
                    builder: (context, snapshot) {
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return Container(
                          height: 150,
                          width: double.infinity,
                          alignment: Alignment.center,
                          child: const CircularProgressIndicator(),
                        );
                      }
                      if (snapshot.hasError || !snapshot.hasData || snapshot.data == null) {
                        return Container(
                          height: 150,
                          width: double.infinity,
                          alignment: Alignment.center,
                          child: const Icon(Icons.error, color: Colors.red, size: 40),
                        );
                      }
                      // Display the image from memory
                      return Image.memory(
                        snapshot.data!,
                        height: 150,
                        width: double.infinity,
                        fit: BoxFit.cover,
                      );
                    },
                  ),
                ),
                // --- END MODIFICATION ---
                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: () => 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")),
              ],
            ),
        ],
      ),
    );
  }
}