// lib/screens/marine/investigative/manual_sampling/marine_inves_manual_step_4_summary.dart

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

import '../../../../auth_provider.dart';
import '../../../../models/marine_inves_manual_sampling_data.dart';
// REMOVED: Import for NPE Report Screen is no longer needed

class MarineInvesManualStep4Summary extends StatefulWidget {
  final MarineInvesManualSamplingData data;
  final Future<Map<String, dynamic>> Function()
  onSubmit; // Expects a function that returns the submission result
  final bool isLoading;

  const MarineInvesManualStep4Summary({
    super.key,
    required this.data,
    required this.onSubmit,
    required this.isLoading,
  });

  @override
  State<MarineInvesManualStep4Summary> createState() => _MarineInvesManualStep4SummaryState();
}

class _MarineInvesManualStep4SummaryState extends State<MarineInvesManualStep4Summary> {
  bool _isHandlingSubmit = false;

  static const Map<String, String> _parameterKeyToLimitName = {
    'oxygenConcentration': 'Oxygen Conc',
    'oxygenSaturation': 'Oxygen Sat',
    'ph': 'pH',
    'salinity': 'Salinity',
    'electricalConductivity': 'Conductivity',
    'temperature': 'Temperature',
    'tds': 'TDS',
    'turbidity': 'Turbidity',
    'tss': 'TSS',
    'batteryVoltage': 'Battery',
  };

  Set<String> _getOutOfBoundsKeys(BuildContext context) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final marineLimits = authProvider.marineParameterLimits ?? [];
    final Set<String> invalidKeys = {};

    int? stationId;
    if (widget.data.stationTypeSelection == 'Existing Manual Station') {
      stationId = widget.data.selectedStation?['station_id'];
    }

    final readings = {
      'oxygenConcentration': widget.data.oxygenConcentration,
      'oxygenSaturation': widget.data.oxygenSaturation,
      'ph': widget.data.ph,
      'salinity': widget.data.salinity,
      'electricalConductivity': widget.data.electricalConductivity,
      'temperature': widget.data.temperature,
      'tds': widget.data.tds,
      'turbidity': widget.data.turbidity,
      'tss': widget.data.tss,
      'batteryVoltage': widget.data.batteryVoltage,
    };

    double? parseLimitValue(dynamic value) {
      if (value == null) return null;
      if (value is num) return value.toDouble();
      if (value is String) return double.tryParse(value);
      return null;
    }

    readings.forEach((key, value) {
      if (value == null || value == -999.0) return;

      final limitName = _parameterKeyToLimitName[key];
      if (limitName == null) return;

      Map<String, dynamic> limitData = {};

      if (stationId != null) {
        limitData = marineLimits.firstWhere(
              (l) =>
          l['param_parameter_list'] == limitName &&
              l['station_id']?.toString() == stationId.toString(),
          orElse: () => {},
        );
      }

      if (limitData.isNotEmpty) {
        final lowerLimit = parseLimitValue(limitData['param_lower_limit']);
        final upperLimit = parseLimitValue(limitData['param_upper_limit']);

        if ((lowerLimit != null && value < lowerLimit) ||
            (upperLimit != null && value > upperLimit)) {
          invalidKeys.add(key);
        }
      }
    });

    return invalidKeys;
  }

  // --- START: ADDED from in-situ module ---
  /// Checks captured data against NPE limits and returns detailed information.
  List<Map<String, dynamic>> _getNpeTriggeredParameters(BuildContext context) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final npeLimits = authProvider.npeParameterLimits ?? [];
    if (npeLimits.isEmpty) return [];

    final List<Map<String, dynamic>> triggeredParams = [];

    final readings = {
      'oxygenConcentration': widget.data.oxygenConcentration,
      'oxygenSaturation': widget.data.oxygenSaturation,
      'ph': widget.data.ph,
      'salinity': widget.data.salinity,
      'electricalConductivity': widget.data.electricalConductivity,
      'temperature': widget.data.temperature,
      'tds': widget.data.tds,
      'turbidity': widget.data.turbidity,
      'tss': widget.data.tss,
    };

    double? parseLimitValue(dynamic value) {
      if (value == null) return null;
      if (value is num) return value.toDouble();
      if (value is String) return double.tryParse(value);
      return null;
    }

    readings.forEach((key, value) {
      if (value == null || value == -999.0) return;
      final limitName = _parameterKeyToLimitName[key];
      if (limitName == null) return;

      // NPE limits are general and NOT station-specific
      final limitData = npeLimits.firstWhere(
            (l) => l['param_parameter_list'] == limitName,
        orElse: () => {},
      );

      if (limitData.isNotEmpty) {
        final lowerLimit = parseLimitValue(limitData['param_lower_limit']);
        final upperLimit = parseLimitValue(limitData['param_upper_limit']);
        bool isHit = false;

        if (lowerLimit != null && upperLimit != null) {
          if (value >= lowerLimit && value <= upperLimit) isHit = true;
        } else if (lowerLimit != null && upperLimit == null) {
          if (value >= lowerLimit) isHit = true;
        } else if (upperLimit != null && lowerLimit == null) {
          if (value <= upperLimit) isHit = true;
        }

        if (isHit) {
          triggeredParams.add({
            'label': limitName,
            'value': value,
            'lower_limit': lowerLimit,
            'upper_limit': upperLimit,
          });
        }
      }
    });
    return triggeredParams;
  }

  /// Displays a SIMPLIFIED NPE warning dialog (no "Open Report" button).
  Future<void> _showNpeWarningDialog(
      BuildContext context, List<Map<String, dynamic>> triggeredParams) async {
    final isDarkTheme = Theme.of(context).brightness == Brightness.dark;

    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext dialogContext) {
        return AlertDialog(
          title: const Text("Notification Pollution Event (NPE 1) Limit Detected"),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                    'The following parameters have fallen under the Notification Pollution Event (NPE) limit:'),
                const SizedBox(height: 16),
                Table(
                  columnWidths: const {
                    0: FlexColumnWidth(2),
                    1: FlexColumnWidth(2.5),
                    2: FlexColumnWidth(1.5),
                  },
                  border: TableBorder(
                    horizontalInside: BorderSide(
                        width: 0.5,
                        color: isDarkTheme
                            ? Colors.grey.shade700
                            : Colors.grey.shade300),
                    verticalInside: BorderSide(
                        width: 0.5,
                        color: isDarkTheme
                            ? Colors.grey.shade700
                            : Colors.grey.shade300),
                    top: BorderSide(
                        width: 1,
                        color: isDarkTheme
                            ? Colors.grey.shade600
                            : Colors.grey.shade400),
                    bottom: BorderSide(
                        width: 1,
                        color: isDarkTheme
                            ? Colors.grey.shade600
                            : Colors.grey.shade400),
                  ),
                  children: [
                    TableRow(
                      decoration: BoxDecoration(
                          color: isDarkTheme
                              ? Colors.grey.shade800
                              : Colors.grey.shade200),
                      children: [
                        Padding(
                            padding: const EdgeInsets.all(6.0),
                            child: Text('Parameter',
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Theme.of(context)
                                        .textTheme
                                        .titleSmall
                                        ?.color))),
                        Padding(
                            padding: const EdgeInsets.all(6.0),
                            child: Text('NPE Range',
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Theme.of(context)
                                        .textTheme
                                        .titleSmall
                                        ?.color))),
                        Padding(
                            padding: const EdgeInsets.all(6.0),
                            child: Text('Current',
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Theme.of(context)
                                        .textTheme
                                        .titleSmall
                                        ?.color))),
                      ],
                    ),
                    ...triggeredParams.map((p) {
                      final lowerStr =
                          p['lower_limit']?.toStringAsFixed(5) ?? 'N/A';
                      final upperStr =
                          p['upper_limit']?.toStringAsFixed(5) ?? 'N/A';
                      String range;
                      if (lowerStr != 'N/A' && upperStr != 'N/A') {
                        range = '$lowerStr - $upperStr';
                      } else if (lowerStr != 'N/A') {
                        range = '>= $lowerStr';
                      } else {
                        range = '<= $upperStr';
                      }

                      return TableRow(
                        children: [
                          Padding(
                              padding: const EdgeInsets.all(6.0),
                              child: Text(p['label'])),
                          Padding(
                              padding: const EdgeInsets.all(6.0),
                              child: Text(range)),
                          Padding(
                            padding: const EdgeInsets.all(6.0),
                            child: Text(
                              p['value'].toStringAsFixed(5),
                              style: const TextStyle(
                                  color: Colors.redAccent,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ],
                      );
                    }).toList(),
                  ],
                ),
                const SizedBox(height: 16),
                const Text('Submission will proceed.'),
              ],
            ),
          ),
          actions: <Widget>[
            ElevatedButton(
              child: const Text("OK"),
              onPressed: () => Navigator.of(dialogContext).pop(),
            ),
          ],
        );
      },
    );
  }
  // --- END: ADDED from in-situ module ---

  // --- START: MODIFIED _handleSubmit ---
  /// Handles the complete submission flow WITH NPE check.
  Future<void> _handleSubmit(BuildContext context) async {
    if (_isHandlingSubmit || widget.isLoading) return;

    setState(() => _isHandlingSubmit = true);

    try {
      // --- NPE CHECK ADDED ---
      final npeParameters = _getNpeTriggeredParameters(context);

      if (npeParameters.isNotEmpty) {
        // Show the warning dialog and wait for the user to press "OK"
        await _showNpeWarningDialog(context, npeParameters);
        if (!mounted) return; // Check mount status after await
      }
      // --- END NPE CHECK ---

      // Proceed with submission after dialog is dismissed (or if not needed)
      final result = await widget.onSubmit();
      if (!mounted) return;

      // Show feedback snackbar based on the result
      final message = result['message'] ?? 'An unknown error occurred.';
      final color = (result['success'] == true) ? Colors.green : Colors.red;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text(message),
            backgroundColor: color,
            duration: const Duration(seconds: 4)),
      );

      // If submission was successful, navigate back to the home screen
      if (result['success'] == true) {
        // No conditional navigation, just go home
        Navigator.of(context).popUntil((route) => route.isFirst);
      }
      // If submission failed, the user stays on the summary screen to potentially retry

    } catch (e) {
      // Catch any unexpected errors during submission
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content: Text('Submission failed unexpectedly: $e'),
              backgroundColor: Colors.red,
              duration: const Duration(seconds: 4)),
        );
      }
    } finally {
      // Ensure the loading state is turned off
      if (mounted) {
        setState(() => _isHandlingSubmit = false);
      }
    }
  }
  // --- END: MODIFIED _handleSubmit ---

  // Helper to build station details dynamically
  List<Widget> _buildStationDetails() {
    final stationType = widget.data.stationTypeSelection;

    if (stationType == 'Existing Manual Station') {
      return [
        _buildDetailRow("Station Source:", "Existing Manual Station"),
        _buildDetailRow("State:", widget.data.selectedManualStateName),
        _buildDetailRow("Category:", widget.data.selectedManualCategoryName),
        _buildDetailRow("Station ID:", widget.data.selectedStation?['man_station_code']?.toString()),
        _buildDetailRow("Station Name:", widget.data.selectedStation?['man_station_name']?.toString()),
        _buildDetailRow("Station Location:", "${widget.data.stationLatitude}, ${widget.data.stationLongitude}"),
      ];
    } else if (stationType == 'Existing Tarball Station') {
      return [
        _buildDetailRow("Station Source:", "Existing Tarball Station"),
        _buildDetailRow("State:", widget.data.selectedTarballStateName),
        _buildDetailRow("Station ID:", widget.data.selectedTarballStation?['tbl_station_code']?.toString()),
        _buildDetailRow("Station Name:", widget.data.selectedTarballStation?['tbl_station_name']?.toString()),
        _buildDetailRow("Station Location:", "${widget.data.stationLatitude}, ${widget.data.stationLongitude}"),
      ];
    } else if (stationType == 'New Location') {
      return [
        _buildDetailRow("Station Source:", "New Location"),
        _buildDetailRow("Station Name:", widget.data.newStationName),
        _buildDetailRow("Station Code:", widget.data.newStationCode),
        _buildDetailRow("Station Location:", "(Manual) ${widget.data.stationLatitude}, ${widget.data.stationLongitude}"),
      ];
    }
    return [_buildDetailRow("Station Info:", "Not specified")];
  }


  @override
  Widget build(BuildContext context) {
    final outOfBoundsKeys = _getOutOfBoundsKeys(context);

    return ListView(
      padding: const EdgeInsets.all(16.0),
      children: [
        Text(
          "Please review all information before submitting.",
          style: Theme.of(context).textTheme.titleMedium,
          textAlign: TextAlign.center,
        ),
        const SizedBox(height: 16),
        _buildSectionCard(
          context,
          "Sampling & Station Details",
          [
            _buildDetailRow("1st Sampler:", widget.data.firstSamplerName),
            _buildDetailRow(
                "2nd Sampler:", widget.data.secondSampler?['first_name']?.toString()),
            _buildDetailRow("Sampling Date:", widget.data.samplingDate),
            _buildDetailRow("Sampling Time:", widget.data.samplingTime),
            _buildDetailRow("Sampling Type:", widget.data.samplingType),
            _buildDetailRow("Sample ID Code:", widget.data.sampleIdCode),
            const Divider(height: 20),
            ..._buildStationDetails(),
          ],
        ),
        _buildSectionCard(
          context,
          "Location & On-Site Info",
          [
            _buildDetailRow("Current Location:",
                "${widget.data.currentLatitude}, ${widget.data.currentLongitude}"),
            _buildDetailRow(
                "Distance Difference:",
                widget.data.distanceDifferenceInKm != null
                    ? "${(widget.data.distanceDifferenceInKm! * 1000).toStringAsFixed(0)} meters"
                    : "N/A"),
            if (widget.data.distanceDifferenceRemarks != null &&
                widget.data.distanceDifferenceRemarks!.isNotEmpty)
              _buildDetailRow(
                  "Distance Remarks:", widget.data.distanceDifferenceRemarks),
            const Divider(height: 20),
            _buildDetailRow("Weather:", widget.data.weather),
            _buildDetailRow("Tide Level:", widget.data.tideLevel),
            _buildDetailRow("Sea Condition:", widget.data.seaCondition),
            _buildDetailRow("Event Remarks:", widget.data.eventRemarks),
            _buildDetailRow("Lab Remarks:", widget.data.labRemarks),
          ],
        ),
        _buildSectionCard(
          context,
          "Attached Photos",
          [
            _buildImageCard("Left Side Land View", widget.data.leftLandViewImage),
            _buildImageCard(
                "Right Side Land View", widget.data.rightLandViewImage),
            _buildImageCard(
                "Filling Water into Bottle", widget.data.waterFillingImage),
            _buildImageCard(
                "Seawater Color in Bottle", widget.data.seawaterColorImage),
            _buildImageCard(
                "Examine Preservative (pH paper)", widget.data.phPaperImage),
            const Divider(height: 24),
            Text("Optional Photos",
                style: Theme.of(context)
                    .textTheme
                    .titleMedium
                    ?.copyWith(fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            _buildImageCard("Optional Photo 1", widget.data.optionalImage1,
                remark: widget.data.optionalRemark1),
            _buildImageCard("Optional Photo 2", widget.data.optionalImage2,
                remark: widget.data.optionalRemark2),
            _buildImageCard("Optional Photo 3", widget.data.optionalImage3,
                remark: widget.data.optionalRemark3),
            _buildImageCard("Optional Photo 4", widget.data.optionalImage4,
                remark: widget.data.optionalRemark4),
          ],
        ),
        _buildSectionCard(
          context,
          "Captured Parameters",
          [
            _buildDetailRow("Sonde ID:", widget.data.sondeId),
            _buildDetailRow("Capture Time:",
                "${widget.data.dataCaptureDate} ${widget.data.dataCaptureTime}"),
            const Divider(height: 20),
            _buildParameterListItem(context,
                icon: Icons.air,
                label: "Oxygen Conc.",
                unit: "mg/L",
                value: widget.data.oxygenConcentration,
                isOutOfBounds:
                outOfBoundsKeys.contains('oxygenConcentration')),
            _buildParameterListItem(context,
                icon: Icons.percent,
                label: "Oxygen Sat.",
                unit: "%",
                value: widget.data.oxygenSaturation,
                isOutOfBounds: outOfBoundsKeys.contains('oxygenSaturation')),
            _buildParameterListItem(context,
                icon: Icons.science_outlined,
                label: "pH",
                unit: "",
                value: widget.data.ph,
                isOutOfBounds: outOfBoundsKeys.contains('ph')),
            _buildParameterListItem(context,
                icon: Icons.waves,
                label: "Salinity",
                unit: "ppt",
                value: widget.data.salinity,
                isOutOfBounds: outOfBoundsKeys.contains('salinity')),
            _buildParameterListItem(context,
                icon: Icons.flash_on,
                label: "Conductivity",
                unit: "µS/cm",
                value: widget.data.electricalConductivity,
                isOutOfBounds:
                outOfBoundsKeys.contains('electricalConductivity')),
            _buildParameterListItem(context,
                icon: Icons.thermostat,
                label: "Temperature",
                unit: "°C",
                value: widget.data.temperature,
                isOutOfBounds: outOfBoundsKeys.contains('temperature')),
            _buildParameterListItem(context,
                icon: Icons.grain,
                label: "TDS",
                unit: "mg/L",
                value: widget.data.tds,
                isOutOfBounds: outOfBoundsKeys.contains('tds')),
            _buildParameterListItem(context,
                icon: Icons.opacity,
                label: "Turbidity",
                unit: "NTU",
                value: widget.data.turbidity,
                isOutOfBounds: outOfBoundsKeys.contains('turbidity')),
            _buildParameterListItem(context,
                icon: Icons.filter_alt_outlined,
                label: "TSS",
                unit: "mg/L",
                value: widget.data.tss,
                isOutOfBounds: outOfBoundsKeys.contains('tss')),
            _buildParameterListItem(context,
                icon: Icons.battery_charging_full,
                label: "Battery",
                unit: "V",
                value: widget.data.batteryVoltage,
                isOutOfBounds: outOfBoundsKeys.contains('batteryVoltage')),
          ],
        ),
        const SizedBox(height: 24),
        (widget.isLoading || _isHandlingSubmit)
            ? const Center(child: CircularProgressIndicator())
            : ElevatedButton.icon(
          onPressed: () => _handleSubmit(context),
          icon: const Icon(Icons.cloud_upload),
          label: const Text('Confirm & Submit'),
          style: ElevatedButton.styleFrom(
            padding: const EdgeInsets.symmetric(vertical: 16),
            textStyle: const TextStyle(
                fontSize: 18, fontWeight: FontWeight.bold),
          ),
        ),
        const SizedBox(height: 16),
      ],
    );
  }

  // --- Helper widgets ---
  Widget _buildSectionCard(
      BuildContext context, String title, List<Widget> children) {
    return Card(
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Theme.of(context).primaryColor,
              ),
            ),
            const Divider(height: 20, thickness: 1),
            ...children,
          ],
        ),
      ),
    );
  }

  Widget _buildDetailRow(String label, String? value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            flex: 2,
            child: Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
          ),
          const SizedBox(width: 8),
          Expanded(
            flex: 3,
            child: Text(value != null && value.isNotEmpty ? value : 'N/A',
                style: const TextStyle(fontSize: 16)),
          ),
        ],
      ),
    );
  }

  Widget _buildParameterListItem(BuildContext context,
      {required IconData icon,
        required String label,
        required String unit,
        required double? value,
        bool isOutOfBounds = false}) {
    final bool isMissing = value == null || value == -999.0;
    final String displayValue =
    isMissing ? 'N/A' : '${value.toStringAsFixed(5)} ${unit}'.trim();
    final Color? defaultTextColor =
        Theme.of(context).textTheme.bodyLarge?.color;
    final Color valueColor = isOutOfBounds
        ? Colors.red
        : (isMissing ? Colors.grey : defaultTextColor ?? Colors.black);

    return ListTile(
      dense: true,
      contentPadding: EdgeInsets.zero,
      leading: Icon(icon, color: Theme.of(context).primaryColor, size: 28),
      title: Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
      trailing: Text(
        displayValue,
        style: Theme.of(context).textTheme.bodyLarge?.copyWith(
          color: valueColor,
          fontWeight: isOutOfBounds ? FontWeight.bold : null,
        ),
      ),
    );
  }

  Widget _buildImageCard(String title, File? image, {String? remark}) {
    final bool hasRemark = remark != null && remark.isNotEmpty;
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(title,
              style:
              const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
          const SizedBox(height: 8),
          if (image != null)
            ClipRRect(
              borderRadius: BorderRadius.circular(8.0),
              child: FutureBuilder<Uint8List>(
                key: ValueKey(image.path),
                future: image.readAsBytes(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return Container(
                      height: 200,
                      width: double.infinity,
                      alignment: Alignment.center,
                      child: const CircularProgressIndicator(),
                    );
                  }
                  if (snapshot.hasError || !snapshot.hasData || snapshot.data == null) {
                    return Container(
                      height: 200,
                      width: double.infinity,
                      alignment: Alignment.center,
                      child: const Icon(Icons.error, color: Colors.red, size: 40),
                    );
                  }
                  return Image.memory(
                    snapshot.data!,
                    height: 200,
                    width: double.infinity,
                    fit: BoxFit.cover,
                  );
                },
              ),
            )
          else
            Container(
              height: 100,
              width: double.infinity,
              decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(8.0),
                  border: Border.all(color: Colors.grey[300]!)),
              child: const Center(
                  child: Text('No Image Attached',
                      style: TextStyle(color: Colors.grey))),
            ),
          if (hasRemark)
            Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: Text('Remark: $remark',
                  style: const TextStyle(fontStyle: FontStyle.italic)),
            ),
        ],
      ),
    );
  }
}