// lib/screens/river/manual/widgets/river_in_situ_step_2_site_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 RiverInSituStep2SiteInfo extends StatefulWidget {
  final RiverInSituSamplingData data;
  final VoidCallback onNext;

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

  @override
  State<RiverInSituStep2SiteInfo> createState() => _RiverInSituStep2SiteInfoState();
}

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

  late final TextEditingController _eventRemarksController;
  late final TextEditingController _labRemarksController;
  final List<String> _weatherOptions = ['Cloudy', 'Drizzle', 'Rainy', 'Sunny', 'Windy'];

  @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();
  }

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

    // Safety check before starting
    if (!mounted) 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
    );

    // --- CRITICAL FIX: Check if widget is still mounted after the await call ---
    // This prevents "Looking up a deactivated widget's ancestor" if user closed camera/app.
    if (!mounted) return;

    if (file != null) {
      setState(() => setImageCallback(file));
    } else if (mounted) {
      _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()) {
      return;
    }

    _formKey.currentState!.save();

    if (widget.data.backgroundStationImage == null ||
        widget.data.upstreamRiverImage == null ||
        widget.data.downstreamRiverImage == null) {
      _showSnackBar('Please attach all 3 required photos 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,
      child: ListView(
        padding: const EdgeInsets.all(24.0),
        children: [
          Text("On-Site Information", style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 16),
          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,
            onSaved: (value) => widget.data.weather = value,
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _eventRemarksController,
            decoration: const InputDecoration(labelText: 'Event Remarks (Optional)', hintText: 'e.g., unusual smells, colors, etc.'),
            onSaved: (value) => widget.data.eventRemarks = value,
            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 Divider(height: 32),

          Text("Required Photos *", style: Theme.of(context).textTheme.titleLarge),
          const Text("All photos must be taken in landscape (horizontal) orientation.", style: TextStyle(color: Colors.grey)),
          const SizedBox(height: 8),

          _buildImagePicker('Background Station', 'BACKGROUND_STATION', widget.data.backgroundStationImage, (file) => widget.data.backgroundStationImage = file, isRequired: true),
          _buildImagePicker('Upstream River', 'UPSTREAM_RIVER', widget.data.upstreamRiverImage, (file) => widget.data.upstreamRiverImage = file, isRequired: true),
          _buildImagePicker('Downstream River', 'DOWNSTREAM_RIVER', widget.data.downstreamRiverImage, (file) => widget.data.downstreamRiverImage = file, isRequired: true),

          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: () => 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)
            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(),
                ),
              ),
            ),
        ],
      ),
    );
  }
}