// lib/screens/marine/manual/tarball_sampling_step2.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:image/image.dart' as img;
import 'package:dropdown_search/dropdown_search.dart';

import 'package:environment_monitoring_app/auth_provider.dart';
import 'package:environment_monitoring_app/models/tarball_data.dart';
import 'package:environment_monitoring_app/screens/marine/manual/tarball_sampling_step3_summary.dart';

class TarballSamplingStep2 extends StatefulWidget {
  final TarballSamplingData data;
  const TarballSamplingStep2({super.key, required this.data});

  @override
  State<TarballSamplingStep2> createState() => _TarballSamplingStep2State();
}

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

  Map<String, dynamic>? _selectedClassification;

  // --- START: MODIFICATION 1 ---
  // Added a state variable to easily check if the classification requires photos.
  // We will assume 'None' classification has an ID of 1. Adjust if necessary.
  bool _isNoneClassificationSelected = false;
  // --- END: MODIFICATION 1 ---

  late final TextEditingController _remark1Controller;
  late final TextEditingController _remark2Controller;
  late final TextEditingController _remark3Controller;
  late final TextEditingController _remark4Controller;

  @override
  void initState() {
    super.initState();

    _remark1Controller = TextEditingController(text: widget.data.optionalRemark1);
    _remark2Controller = TextEditingController(text: widget.data.optionalRemark2);
    _remark3Controller = TextEditingController(text: widget.data.optionalRemark3);
    _remark4Controller = TextEditingController(text: widget.data.optionalRemark4);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      final auth = Provider.of<AuthProvider>(context, listen: false);

      if (widget.data.classificationId != null && auth.tarballClassifications != null) {
        try {
          final foundClassification = auth.tarballClassifications!.firstWhere(
                (c) => c['classification_id'] == widget.data.classificationId,
          );
          setState(() {
            _selectedClassification = foundClassification;
            widget.data.selectedClassification = foundClassification;
            // --- START: MODIFICATION 2 ---
            // Update our state variable when restoring the form state.
            _isNoneClassificationSelected = widget.data.classificationId == 1;
            // --- END: MODIFICATION 2 ---
          });
        } catch (e) {
          debugPrint("Could not find pre-selected classification in the cached list.");
        }
      }
      auth.syncAllData();
    });
  }

  @override
  void dispose() {
    _remark1Controller.dispose();
    _remark2Controller.dispose();
    _remark3Controller.dispose();
    _remark4Controller.dispose();
    super.dispose();
  }

  void _showOrientationDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("Incorrect Image Orientation"),
          content: const Text("All photos must be taken in a vertical (landscape) orientation."),
          actions: [
            TextButton(
              child: const Text("OK"),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
        );
      },
    );
  }

  Future<File?> _pickAndProcessImage(ImageSource source, String imageInfo) async {
    if (_isPickingImage) return null;
    setState(() => _isPickingImage = true);

    final picker = ImagePicker();
    final XFile? photo = await picker.pickImage(source: source, imageQuality: 85, maxWidth: 1024);

    if (photo == null) {
      setState(() => _isPickingImage = false);
      return null;
    }

    final bytes = await photo.readAsBytes();
    img.Image? originalImage = img.decodeImage(bytes);
    if (originalImage == null) {
      setState(() => _isPickingImage = false);
      return null;
    }

    if (originalImage.height > originalImage.width) {
      _showOrientationDialog();
      setState(() => _isPickingImage = false);
      return null;
    }

    final String watermarkTimestamp = "${widget.data.samplingDate} ${widget.data.samplingTime}";
    final font = img.arial24;
    const int padding = 10;

    final textWidth = watermarkTimestamp.length * 12;
    final textHeight = 24;
    img.fillRect(
      originalImage,
      x1: padding - 5,
      y1: padding - 5,
      x2: padding + textWidth + 5,
      y2: padding + textHeight + 5,
      color: img.ColorRgb8(255, 255, 255),
    );

    img.drawString(
      originalImage,
      watermarkTimestamp,
      font: font,
      x: padding,
      y: padding,
      color: img.ColorRgb8(0, 0, 0),
    );

    final stationCode = widget.data.selectedStation?['tbl_station_code'] ?? 'NO_STATION';
    final fileTimestamp = "${widget.data.samplingDate}-${widget.data.samplingTime}".replaceAll(':', '-');
    final sanitizedImageInfo = imageInfo.replaceAll(' ', '').toUpperCase();
    final newFileName = "${stationCode}_${fileTimestamp}_${sanitizedImageInfo}.jpg";

    final tempDir = await getTemporaryDirectory();
    final filePath = path.join(tempDir.path, newFileName);

    final File processedFile = File(filePath)..writeAsBytesSync(img.encodeJpg(originalImage));

    setState(() => _isPickingImage = false);
    return processedFile;
  }

  void _setImage(Function(File?) setImageCallback, ImageSource source, String imageInfo) async {
    final file = await _pickAndProcessImage(source, imageInfo);
    if (file != null) {
      setState(() {
        setImageCallback(file);
      });
    }
  }

  void _goToNextStep() {
    if (_formKey.currentState!.validate()) {
      if (widget.data.classificationId == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Please select a tarball classification before proceeding.'),
            backgroundColor: Colors.red,
          ),
        );
        return;
      }

      if (widget.data.leftCoastalViewImage == null ||
          widget.data.rightCoastalViewImage == null ||
          widget.data.verticalLinesImage == null ||
          widget.data.horizontalLineImage == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Please attach all required photos before proceeding.'),
            backgroundColor: Colors.red,
          ),
        );
        return;
      }

      // --- START: MODIFICATION 3 ---
      // This is the new validation logic.
      // If the classification is NOT "None", we check if Optional Photo 1 and its remark have been provided.
      if (!_isNoneClassificationSelected) {
        if (widget.data.optionalImage1 == null || _remark1Controller.text.trim().isEmpty) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Optional Photo 1 and its remark are mandatory for this classification.'),
              backgroundColor: Colors.red,
            ),
          );
          return;
        }
      }
      // --- END: MODIFICATION 3 ---

      // This is the existing validation you already had, which is still correct.
      if (widget.data.optionalImage1 != null && _remark1Controller.text.trim().isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('A remark is required for Optional Photo 1.'), backgroundColor: Colors.red),
        );
        return;
      }
      if (widget.data.optionalImage2 != null && _remark2Controller.text.trim().isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('A remark is required for Optional Photo 2.'), backgroundColor: Colors.red),
        );
        return;
      }
      if (widget.data.optionalImage3 != null && _remark3Controller.text.trim().isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('A remark is required for Optional Photo 3.'), backgroundColor: Colors.red),
        );
        return;
      }
      if (widget.data.optionalImage4 != null && _remark4Controller.text.trim().isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('A remark is required for Optional Photo 4.'), backgroundColor: Colors.red),
        );
        return;
      }

      widget.data.optionalRemark1 = _remark1Controller.text;
      widget.data.optionalRemark2 = _remark2Controller.text;
      widget.data.optionalRemark3 = _remark3Controller.text;
      widget.data.optionalRemark4 = _remark4Controller.text;

      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => TarballSamplingStep3Summary(data: widget.data)),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("On-Site Info (2/3)")),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(24.0),
          children: [
            Text("On-Site Information", style: Theme.of(context).textTheme.headlineSmall),
            const SizedBox(height: 24),

            Consumer<AuthProvider>(
              builder: (context, auth, child) {
                final classifications = auth.tarballClassifications;
                final bool isEnabled = classifications != null;

                return DropdownSearch<Map<String, dynamic>>(
                  items: classifications ?? [],
                  selectedItem: _selectedClassification,
                  enabled: isEnabled,
                  itemAsString: (item) => item['classification_name'] as String,
                  dropdownDecoratorProps: DropDownDecoratorProps(
                    dropdownSearchDecoration: InputDecoration(
                      labelText: "Tarball Classification *",
                      hintText: isEnabled ? "Select a classification" : "Loading classifications...",
                    ),
                  ),
                  popupProps: const PopupProps.menu(
                    showSearchBox: true,
                    searchFieldProps: TextFieldProps(
                      decoration: InputDecoration(hintText: "Search Classification..."),
                    ),
                  ),
                  onChanged: (value) {
                    setState(() {
                      _selectedClassification = value;
                      widget.data.selectedClassification = value;
                      widget.data.classificationId = value?['classification_id'];

                      // --- START: MODIFICATION 4 ---
                      // Update the state variable whenever the dropdown changes.
                      // This will drive the conditional UI and validation.
                      _isNoneClassificationSelected = widget.data.classificationId == 1;

                      // If user switches back to 'None', clear out old optional data
                      if (_isNoneClassificationSelected) {
                        widget.data.optionalImage1 = null;
                        widget.data.optionalRemark1 = null;
                        _remark1Controller.clear();
                        // You might want to clear others too if needed
                      }
                      // --- END: MODIFICATION 4 ---
                    });
                  },
                  validator: (value) => value == null ? 'Classification is required' : null,
                );
              },
            ),

            const SizedBox(height: 24),
            Text("Required Photos *", style: Theme.of(context).textTheme.titleLarge),
            _buildImagePicker('Left Side Coastal View', 'LEFTSIDECOASTALVIEW', widget.data.leftCoastalViewImage, (file) => widget.data.leftCoastalViewImage = file, isRequired: true),
            _buildImagePicker('Right Side Coastal View', 'RIGHTSIDECOASTALVIEW', widget.data.rightCoastalViewImage, (file) => widget.data.rightCoastalViewImage = file, isRequired: true),
            _buildImagePicker('Drawing Vertical Lines', 'VERTICALLINES', widget.data.verticalLinesImage, (file) => widget.data.verticalLinesImage = file, isRequired: true),
            _buildImagePicker('Drawing Horizontal Lines (Racking)', 'HORIZONTALLINE', widget.data.horizontalLineImage, (file) => widget.data.horizontalLineImage = file, isRequired: true),

            // --- START: MODIFICATION 5 ---
            // Wrap the entire "Optional Photos" section in a Visibility widget.
            // It will only be visible if a classification has been selected AND it's not the "None" classification.
            Visibility(
              visible: _selectedClassification != null && !_isNoneClassificationSelected,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(height: 24),
                  Text("Optional Photos & Remarks", style: Theme.of(context).textTheme.titleLarge),
                  const SizedBox(height: 8),
                  // For the first optional photo, we now mark it as required.
                  _buildImagePicker('Optional Photo 1', 'OPTIONAL1', widget.data.optionalImage1, (file) => widget.data.optionalImage1 = file, remarkController: _remark1Controller, isRequired: true),
                  _buildImagePicker('Optional Photo 2', 'OPTIONAL2', widget.data.optionalImage2, (file) => widget.data.optionalImage2 = file, remarkController: _remark2Controller),
                  _buildImagePicker('Optional Photo 3', 'OPTIONAL3', widget.data.optionalImage3, (file) => widget.data.optionalImage3 = file, remarkController: _remark3Controller),
                  _buildImagePicker('Optional Photo 4', 'OPTIONAL4', widget.data.optionalImage4, (file) => widget.data.optionalImage4 = file, remarkController: _remark4Controller),
                ],
              ),
            ),
            // --- END: MODIFICATION 5 ---

            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), icon: const Icon(Icons.camera_alt), label: const Text("Camera")),
                ElevatedButton.icon(onPressed: _isPickingImage ? null : () => _setImage(setImageCallback, ImageSource.gallery, imageInfo), 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' + (isRequired ? ' *' : ''), // Also indicate required status here
                  hintText: 'Add a remark...',
                  border: const OutlineInputBorder(),
                ),
              ),
            ),
        ],
      ),
    );
  }
}