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

import 'dart:io';
import 'package:flutter/material.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,
  });

  @override
  Widget build(BuildContext 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:", 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),
            _buildParameterListItem(context, icon: Icons.air, label: "Oxygen Conc.", unit: "mg/L", value: data.oxygenConcentration?.toStringAsFixed(2)),
            _buildParameterListItem(context, icon: Icons.percent, label: "Oxygen Sat.", unit: "%", value: data.oxygenSaturation?.toStringAsFixed(2)),
            _buildParameterListItem(context, icon: Icons.science_outlined, label: "pH", unit: "", value: data.ph?.toStringAsFixed(2)),
            _buildParameterListItem(context, icon: Icons.waves, label: "Salinity", unit: "ppt", value: data.salinity?.toStringAsFixed(2)),
            _buildParameterListItem(context, icon: Icons.flash_on, label: "Conductivity", unit: "µS/cm", value: data.electricalConductivity?.toStringAsFixed(0)),
            _buildParameterListItem(context, icon: Icons.thermostat, label: "Temperature", unit: "°C", value: data.temperature?.toStringAsFixed(2)),
            _buildParameterListItem(context, icon: Icons.grain, label: "TDS", unit: "mg/L", value: data.tds?.toStringAsFixed(2)),
            _buildParameterListItem(context, icon: Icons.opacity, label: "Turbidity", unit: "NTU", value: data.turbidity?.toStringAsFixed(2)),
            _buildParameterListItem(context, icon: Icons.filter_alt_outlined, label: "TSS", unit: "mg/L", value: data.tss?.toStringAsFixed(2)),
            _buildParameterListItem(context, icon: Icons.battery_charging_full, label: "Battery", unit: "V", value: data.batteryVoltage?.toStringAsFixed(2)),

            // ADDED: Display for Flowrate
            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)),
          ),
        ],
      ),
    );
  }

  Widget _buildParameterListItem(BuildContext context, {required IconData icon, required String label, required String unit, required String? value}) {
    final bool isMissing = value == null || value.contains('-999');
    final String displayValue = isMissing ? 'N/A' : '$value ${unit}'.trim();

    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: isMissing ? Colors.grey : null,
          fontWeight: isMissing ? null : FontWeight.bold,
        ),
      ),
    );
  }

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

  // ADDED: Widget to build the flowrate summary section
  Widget _buildFlowrateSummary(BuildContext context) {
    final method = data.flowrateMethod ?? 'N/A';
    final value = data.flowrateValue != null ? '${data.flowrateValue!.toStringAsFixed(4)} m/s' : 'NA';

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildDetailRow("Flowrate Method:", method),
        if (method == 'Surface Drifter') ...[
          _buildDetailRow("  Height:", data.flowrateSurfaceDrifterHeight?.toString()),
          _buildDetailRow("  Distance:", data.flowrateSurfaceDrifterDistance?.toString()),
          _buildDetailRow("  Time First:", data.flowrateSurfaceDrifterTimeFirst),
          _buildDetailRow("  Time Last:", data.flowrateSurfaceDrifterTimeLast),
        ],
        _buildDetailRow("Flowrate Value:", value),
      ],
    );
  }
}
