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

import '../../../../models/in_situ_sampling_data.dart';

class InSituStep4Summary extends StatelessWidget {
  final InSituSamplingData data;
  final VoidCallback onSubmit;
  final bool isLoading;

  const InSituStep4Summary({
    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("Category:", data.selectedCategoryName),
            _buildDetailRow("Station Code:", data.selectedStation?['man_station_code']?.toString()),
            _buildDetailRow("Station Name:", data.selectedStation?['man_station_name']?.toString()),
            _buildDetailRow("Station Location:", "${data.stationLatitude}, ${data.stationLongitude}"),
          ],
        ),

        _buildSectionCard(
          context,
          "Location & On-Site Info",
          [
            _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("Tide Level:", data.tideLevel),
            _buildDetailRow("Sea Condition:", data.seaCondition),
            _buildDetailRow("Event Remarks:", data.eventRemarks),
            _buildDetailRow("Lab Remarks:", data.labRemarks),
          ],
        ),

        _buildSectionCard(
          context,
          "Attached Photos",
          [
            _buildImageCard("Left Side Land View", data.leftLandViewImage),
            _buildImageCard("Right Side Land View", data.rightLandViewImage),
            _buildImageCard("Filling Water into Bottle", data.waterFillingImage),
            _buildImageCard("Seawater Color in Bottle", data.seawaterColorImage),
            _buildImageCard("Examine Preservative (pH paper)", 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", 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)),
          ],
        ),

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

  /// A reusable widget to create a consistent section card.
  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,
          ],
        ),
      ),
    );
  }

  /// A reusable widget for a label-value row.
  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 String? value}) {
    // REPAIRED: Only check if the value is null. It will now display numerical
    // values like -999.00 instead of converting them to 'N/A'.
    final bool isMissing = value == null;
    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,
        ),
      ),
    );
  }

  /// A reusable widget to display an attached image or a placeholder.
  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)),
            ),
        ],
      ),
    );
  }
}