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

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;

  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((_) {
      if (widget.data.classificationId != null) {
        final auth = Provider.of<AuthProvider>(context, listen: false);
        final classifications = auth.tarballClassifications ?? [];
        if (classifications.isNotEmpty) {
          try {
            final foundClassification = classifications.firstWhere(
                  (c) => c['classification_id'] == widget.data.classificationId,
            );
            if (mounted) {
              setState(() {
                _selectedClassification = foundClassification;
              });
            }
          } catch (e) {
            debugPrint("Could not find pre-selected classification with ID: ${widget.data.classificationId}");
          }
        }
      }
    });
  }

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

  /// Shows a dialog to the user informing them about the image orientation requirement.
  void _showOrientationDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("Incorrect Image Orientation"),
          content: const Text("Required photos must be taken in a horizontal (landscape) orientation."),
          actions: [
            TextButton(
              child: const Text("OK"),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
        );
      },
    );
  }

  /// Picks an image, processes it (checks orientation, adds watermark), and returns the file.
  Future<File?> _pickAndProcessImage(ImageSource source, String imageInfo, {required bool isRequired}) 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;
    }

    // --- NEW: Validate image orientation for required photos ---
    if (isRequired && originalImage.height > originalImage.width) {
      _showOrientationDialog();
      setState(() => _isPickingImage = false);
      return null; // Reject the vertical image
    }

    // --- MODIFIED: Reduced watermark font size ---
    final String watermarkTimestamp = "${widget.data.samplingDate} ${widget.data.samplingTime}";
    final font = img.arial24; // Reduced from arial48
    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 processedFile = await File(filePath).writeAsBytes(img.encodeJpg(originalImage));

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

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

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

      // --- NEW: Validate that all required photos have been attached ---
      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; // Stop the function if validation fails
      }

      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) {
                if (auth.tarballClassifications == null || auth.tarballClassifications!.isEmpty) {
                  return DropdownButtonFormField<String>(
                    decoration: const InputDecoration(
                      labelText: 'Tarball Classification *',
                      hintText: 'Loading or no classifications found...',
                    ),
                    items: const [],
                    onChanged: null,
                  );
                }

                return DropdownButtonFormField<Map<String, dynamic>>(
                  decoration: const InputDecoration(labelText: 'Tarball Classification *'),
                  value: _selectedClassification,
                  items: auth.tarballClassifications!.map((classification) {
                    return DropdownMenuItem<Map<String, dynamic>>(
                      value: classification,
                      child: Text(classification['classification_name']?.toString() ?? 'Unnamed'),
                    );
                  }).toList(),
                  onChanged: (value) {
                    setState(() {
                      _selectedClassification = value;
                      widget.data.classificationId = value?['classification_id'];
                    });
                  },
                  validator: (value) => value == null ? 'Classification is required' : null,
                );
              },
            ),

            const SizedBox(height: 24),
            // --- MODIFIED: Added asterisk to indicate required section ---
            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 Line', 'HORIZONTALLINE', widget.data.horizontalLineImage, (file) => widget.data.horizontalLineImage = file, isRequired: true),

            const SizedBox(height: 24),
            Text("Optional Photos & Remarks", style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 8),
            _buildImagePicker('Optional Photo 1', 'OPTIONAL1', widget.data.optionalImage1, (file) => widget.data.optionalImage1 = file, remarkController: _remark1Controller),
            _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),

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

  // --- MODIFIED: Added isRequired flag ---
  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: [
          // --- MODIFIED: Add asterisk to title if required ---
          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(),
                ),
              ),
            ),
        ],
      ),
    );
  }
}
