// lib/screens/river/manual/widgets/river_in_situ_step_5_summary.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../../../auth_provider.dart';
import '../../../../models/river_in_situ_sampling_data.dart';

class RiverInSituStep5Summary extends StatelessWidget {
  final RiverInSituSamplingData data;
  final VoidCallback onSubmit;
  final bool isLoading;

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

  // --- START: MODIFICATION FOR HIGHLIGHTING ---
  // Added helper logic to re-validate parameters on the summary screen.

  /// Maps the app's internal parameter keys to the names used in the database.
  static const Map<String, String> _parameterKeyToLimitName = {
    'oxygenConcentration': 'Oxygen Conc',
    'oxygenSaturation': 'Oxygen Sat',
    'ph': 'pH',
    'salinity': 'Salinity',
    'electricalConductivity': 'Conductivity',
    'temperature': 'Temperature',
    'tds': 'TDS',
    'turbidity': 'Turbidity',
    'ammonia': 'Ammonia',
    'batteryVoltage': 'Battery',
  };

  /// Re-validates the final parameters against the defined limits.
  Set<String> _getOutOfBoundsKeys(BuildContext context) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    // --- MODIFICATION: Use the new river-specific parameter limits list ---
    final riverLimits = authProvider.riverParameterLimits ?? [];
    // --- END MODIFICATION ---
    final Set<String> invalidKeys = {};

    final readings = {
      'oxygenConcentration': data.oxygenConcentration, 'oxygenSaturation': data.oxygenSaturation,
      'ph': data.ph, 'salinity': data.salinity, 'electricalConductivity': data.electricalConductivity,
      'temperature': data.temperature, 'tds': data.tds, 'turbidity': data.turbidity,
      'ammonia': data.ammonia, 'batteryVoltage': 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;

      final limitData = riverLimits.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']);

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

    return invalidKeys;
  }
  // --- END: MODIFICATION FOR HIGHLIGHTING ---

  @override
  Widget build(BuildContext context) {
    // --- START: MODIFICATION FOR HIGHLIGHTING ---
    // Get the set of out-of-bounds keys before building the list.
    final outOfBoundsKeys = _getOutOfBoundsKeys(context);
    // --- END: MODIFICATION FOR HIGHLIGHTING ---

    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:", data.firstSamplerName),
            _buildDetailRow("2nd Sampler:", data.secondSampler?['first_name']?.toString()),
            _buildDetailRow("Sampling Date:", data.samplingDate),
            _buildDetailRow("Sampling Time:", data.samplingTime),
            _buildDetailRow("Sampling Type:", data.samplingType),
            _buildDetailRow("Sample ID Code:", data.sampleIdCode),
            const Divider(height: 20),
            _buildDetailRow("State:", data.selectedStateName),
            _buildDetailRow(
                "Station:",
                "${data.selectedStation?['sampling_station_code']} | ${data.selectedStation?['sampling_river']} | ${data.selectedStation?['sampling_basin']}"
            ),
            _buildDetailRow("Station Location:", "${data.stationLatitude}, ${data.stationLongitude}"),
          ],
        ),

        _buildSectionCard(
          context,
          "Site Info & Required Photos",
          [
            _buildDetailRow("Current Location:", "${data.currentLatitude}, ${data.currentLongitude}"),
            _buildDetailRow("Distance Difference:", data.distanceDifferenceInKm != null ? "${(data.distanceDifferenceInKm! * 1000).toStringAsFixed(0)} meters" : "N/A"),
            if (data.distanceDifferenceRemarks != null && data.distanceDifferenceRemarks!.isNotEmpty)
              _buildDetailRow("Distance Remarks:", data.distanceDifferenceRemarks),
            const Divider(height: 20),

            _buildDetailRow("Weather:", data.weather),
            _buildDetailRow("Event Remarks:", data.eventRemarks),
            _buildDetailRow("Lab Remarks:", data.labRemarks),
            const Divider(height: 20),

            _buildImageCard("Background Station", data.backgroundStationImage),
            _buildImageCard("Upstream River", data.upstreamRiverImage),
            _buildImageCard("Downstream River", data.downstreamRiverImage),
          ],
        ),

        _buildSectionCard(
          context,
          "Additional Photos & Remarks",
          [
            _buildImageCard("Sample Turbidity", data.sampleTurbidityImage),
            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", data.optionalImage1, remark: data.optionalRemark1),
            _buildImageCard("Optional Photo 2", data.optionalImage2, remark: data.optionalRemark2),
            _buildImageCard("Optional Photo 3", data.optionalImage3, remark: data.optionalRemark3),
            _buildImageCard("Optional Photo 4", data.optionalImage4, remark: data.optionalRemark4),
          ],
        ),

        _buildSectionCard(
          context,
          "Captured Parameters",
          [
            _buildDetailRow("Sonde ID:", data.sondeId),
            _buildDetailRow("Capture Time:", "${data.dataCaptureDate} ${data.dataCaptureTime}"),
            const Divider(height: 20),
            // --- START: MODIFICATION FOR 5 DECIMALS & HIGHLIGHTING ---
            _buildParameterListItem(context, icon: Icons.air, label: "Oxygen Conc.", unit: "mg/L", value: data.oxygenConcentration, isOutOfBounds: outOfBoundsKeys.contains('oxygenConcentration')),
            _buildParameterListItem(context, icon: Icons.percent, label: "Oxygen Sat.", unit: "%", value: data.oxygenSaturation, isOutOfBounds: outOfBoundsKeys.contains('oxygenSaturation')),
            _buildParameterListItem(context, icon: Icons.science_outlined, label: "pH", unit: "", value: data.ph, isOutOfBounds: outOfBoundsKeys.contains('ph')),
            _buildParameterListItem(context, icon: Icons.waves, label: "Salinity", unit: "ppt", value: data.salinity, isOutOfBounds: outOfBoundsKeys.contains('salinity')),
            _buildParameterListItem(context, icon: Icons.flash_on, label: "Conductivity", unit: "µS/cm", value: data.electricalConductivity, isOutOfBounds: outOfBoundsKeys.contains('electricalConductivity')),
            _buildParameterListItem(context, icon: Icons.thermostat, label: "Temperature", unit: "°C", value: data.temperature, isOutOfBounds: outOfBoundsKeys.contains('temperature')),
            _buildParameterListItem(context, icon: Icons.grain, label: "TDS", unit: "mg/L", value: data.tds, isOutOfBounds: outOfBoundsKeys.contains('tds')),
            _buildParameterListItem(context, icon: Icons.opacity, label: "Turbidity", unit: "NTU", value: data.turbidity, isOutOfBounds: outOfBoundsKeys.contains('turbidity')),
            _buildParameterListItem(context, icon: Icons.science, label: "Ammonia", unit: "mg/L", value: data.ammonia, isOutOfBounds: outOfBoundsKeys.contains('ammonia')),
            _buildParameterListItem(context, icon: Icons.battery_charging_full, label: "Battery", unit: "V", value: data.batteryVoltage, isOutOfBounds: outOfBoundsKeys.contains('batteryVoltage')),
            // --- END: MODIFICATION ---
            const Divider(height: 20),
            _buildFlowrateSummary(context),
          ],
        ),

        const SizedBox(height: 24),
        isLoading
            ? const Center(child: CircularProgressIndicator())
            : ElevatedButton.icon(
          onPressed: onSubmit,
          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),
      ],
    );
  }

  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) {
    String displayValue = value?.replaceAll('null - null', '').replaceAll('null |', '').replaceAll('| null', '').trim() ?? 'N/A';
    if (displayValue.isEmpty || displayValue == "-") {
      displayValue = 'N/A';
    }

    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(displayValue, style: const TextStyle(fontSize: 16)),
          ),
        ],
      ),
    );
  }

  // --- START: MODIFICATION FOR 5 DECIMALS & HIGHLIGHTING ---
  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;
    // Format the value to 5 decimal places if it's a valid number.
    final String displayValue = isMissing ? 'N/A' : '${value.toStringAsFixed(5)} ${unit}'.trim();

    // Determine the color for the value based on theme and status.
    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,
        ),
      ),
    );
  }
  // --- END: MODIFICATION ---

  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: Image.file(image, key: UniqueKey(), 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)),
            ),
        ],
      ),
    );
  }

  Widget _buildFlowrateSummary(BuildContext context) {
    final method = data.flowrateMethod ?? 'N/A';

    List<Widget> children = [
      _buildDetailRow("Flowrate Method:", method),
    ];

    if (method == 'Surface Drifter') {
      children.add(
          Padding(
            padding: const EdgeInsets.only(left: 16.0, top: 4.0),
            child: Column(
              children: [
                _buildDetailRow("Height:", data.flowrateSurfaceDrifterHeight != null ? "${data.flowrateSurfaceDrifterHeight} m" : "N/A"),
                _buildDetailRow("Distance:", data.flowrateSurfaceDrifterDistance != null ? "${data.flowrateSurfaceDrifterDistance} m" : "N/A"),
                _buildDetailRow("Time First:", data.flowrateSurfaceDrifterTimeFirst ?? "N/A"),
                _buildDetailRow("Time Last:", data.flowrateSurfaceDrifterTimeLast ?? "N/A"),
              ],
            ),
          )
      );
    }

    children.add(
        _buildDetailRow("Flowrate Value:", data.flowrateValue != null ? '${data.flowrateValue!.toStringAsFixed(4)} m/s' : 'NA')
    );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: children,
    );
  }
}