// lib/models/river_in_situ_sampling_data.dart

import 'dart:io';

/// A data model class to hold all information for the multi-step
/// River In-Situ Sampling form.
class RiverInSituSamplingData {
  // --- Step 1: Sampling & Station Info ---
  String? firstSamplerName;
  int? firstSamplerUserId;
  Map<String, dynamic>? secondSampler;
  String? samplingDate;
  String? samplingTime;
  String? samplingType;
  String? sampleIdCode;

  String? selectedStateName;
  String? selectedCategoryName;
  Map<String, dynamic>? selectedStation;

  String? stationLatitude;
  String? stationLongitude;
  String? currentLatitude;
  String? currentLongitude;
  double? distanceDifferenceInKm;
  String? distanceDifferenceRemarks;

  // --- Step 2: Site Info & Photos ---
  String? weather;
  String? eventRemarks;
  String? labRemarks;

  File? backgroundStationImage;
  File? upstreamRiverImage;
  File? downstreamRiverImage;

  // --- Step 4: Additional Photos ---
  File? sampleTurbidityImage;

  File? optionalImage1;
  String? optionalRemark1;
  File? optionalImage2;
  String? optionalRemark2;
  File? optionalImage3;
  String? optionalRemark3;
  File? optionalImage4;
  String? optionalRemark4;

  // --- Step 3: Data Capture ---
  String? sondeId;
  String? dataCaptureDate;
  String? dataCaptureTime;
  double? oxygenConcentration;
  double? oxygenSaturation;
  double? ph;
  double? salinity;
  double? electricalConductivity;
  double? temperature;
  double? tds;
  double? turbidity;
  double? tss;
  double? batteryVoltage;

  // ADDED: New properties for Flowrate
  String? flowrateMethod; // 'Surface Drifter', 'Flowmeter', 'NA'
  double? flowrateSurfaceDrifterHeight;
  double? flowrateSurfaceDrifterDistance;
  String? flowrateSurfaceDrifterTimeFirst;
  String? flowrateSurfaceDrifterTimeLast;
  double? flowrateValue;


  // --- Post-Submission Status ---
  String? submissionStatus;
  String? submissionMessage;
  String? reportId;

  RiverInSituSamplingData({
    this.samplingDate,
    this.samplingTime,
  });

  factory RiverInSituSamplingData.fromJson(Map<String, dynamic> json) {
    File? fileFromJson(dynamic path) {
      return (path is String && path.isNotEmpty) ? File(path) : null;
    }

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

    // ADDED HELPER FUNCTION TO FIX THE ERROR
    int? intFromJson(dynamic value) {
      if (value is int) return value;
      if (value is String) return int.tryParse(value);
      return null;
    }

    return RiverInSituSamplingData()
      ..firstSamplerName = json['first_sampler_name']
    // MODIFIED THIS LINE TO USE THE HELPER FUNCTION
      ..firstSamplerUserId = intFromJson(json['first_sampler_user_id'])
      ..secondSampler = json['secondSampler']
      ..samplingDate = json['r_man_date']
      ..samplingTime = json['r_man_time']
      ..samplingType = json['r_man_type']
      ..sampleIdCode = json['r_man_sample_id_code']
      ..selectedStateName = json['selectedStateName']
      ..selectedCategoryName = json['selectedCategoryName']
      ..selectedStation = json['selectedStation']
      ..stationLatitude = json['stationLatitude']
      ..stationLongitude = json['stationLongitude']
      ..currentLatitude = json['r_man_current_latitude']?.toString()
      ..currentLongitude = json['r_man_current_longitude']?.toString()
      ..distanceDifferenceInKm = doubleFromJson(json['r_man_distance_difference'])
      ..distanceDifferenceRemarks = json['r_man_distance_difference_remarks']
      ..weather = json['r_man_weather']
      ..eventRemarks = json['r_man_event_remark']
      ..labRemarks = json['r_man_lab_remark']
      ..sondeId = json['r_man_sondeID']
      ..dataCaptureDate = json['data_capture_date']
      ..dataCaptureTime = json['data_capture_time']
      ..oxygenConcentration = doubleFromJson(json['r_man_oxygen_conc'])
      ..oxygenSaturation = doubleFromJson(json['r_man_oxygen_sat'])
      ..ph = doubleFromJson(json['r_man_ph'])
      ..salinity = doubleFromJson(json['r_man_salinity'])
      ..electricalConductivity = doubleFromJson(json['r_man_conductivity'])
      ..temperature = doubleFromJson(json['r_man_temperature'])
      ..tds = doubleFromJson(json['r_man_tds'])
      ..turbidity = doubleFromJson(json['r_man_turbidity'])
      ..tss = doubleFromJson(json['r_man_tss'])
      ..batteryVoltage = doubleFromJson(json['r_man_battery_volt'])
      ..optionalRemark1 = json['r_man_optional_photo_01_remarks']
      ..optionalRemark2 = json['r_man_optional_photo_02_remarks']
      ..optionalRemark3 = json['r_man_optional_photo_03_remarks']
      ..optionalRemark4 = json['r_man_optional_photo_04_remarks']
      ..backgroundStationImage = fileFromJson(json['r_man_background_station'])
      ..upstreamRiverImage = fileFromJson(json['r_man_upstream_river'])
      ..downstreamRiverImage = fileFromJson(json['r_man_downstream_river'])
      ..sampleTurbidityImage = fileFromJson(json['r_man_sample_turbidity'])
      ..optionalImage1 = fileFromJson(json['r_man_optional_photo_01'])
      ..optionalImage2 = fileFromJson(json['r_man_optional_photo_02'])
      ..optionalImage3 = fileFromJson(json['r_man_optional_photo_03'])
      ..optionalImage4 = fileFromJson(json['r_man_optional_photo_04'])
    // ADDED: Flowrate fields from JSON
      ..flowrateMethod = json['r_man_flowrate_method']
      ..flowrateSurfaceDrifterHeight = doubleFromJson(json['r_man_flowrate_sd_height'])
      ..flowrateSurfaceDrifterDistance = doubleFromJson(json['r_man_flowrate_sd_distance'])
      ..flowrateSurfaceDrifterTimeFirst = json['r_man_flowrate_sd_time_first']
      ..flowrateSurfaceDrifterTimeLast = json['r_man_flowrate_sd_time_last']
      ..flowrateValue = doubleFromJson(json['r_man_flowrate_value']);
  }


  /// Converts the data model into a Map<String, String> for the API form data.
  Map<String, String> toApiFormData() {
    final Map<String, String> map = {};

    void add(String key, dynamic value) {
      if (value != null) {
        map[key] = value.toString();
      }
    }

    // Step 1 Data
    add('first_sampler_user_id', firstSamplerUserId);
    add('r_man_second_sampler_id', secondSampler?['user_id']);
    add('r_man_date', samplingDate);
    add('r_man_time', samplingTime);
    add('r_man_type', samplingType);
    add('r_man_sample_id_code', sampleIdCode);
    add('station_id', selectedStation?['station_id']);
    add('r_man_current_latitude', currentLatitude);
    add('r_man_current_longitude', currentLongitude);
    add('r_man_distance_difference', distanceDifferenceInKm);
    add('r_man_distance_difference_remarks', distanceDifferenceRemarks);

    // Step 2 Data
    add('r_man_weather', weather);
    add('r_man_event_remark', eventRemarks);
    add('r_man_lab_remark', labRemarks);

    // Step 4 Data
    add('r_man_optional_photo_01_remarks', optionalRemark1);
    add('r_man_optional_photo_02_remarks', optionalRemark2);
    add('r_man_optional_photo_03_remarks', optionalRemark3);
    add('r_man_optional_photo_04_remarks', optionalRemark4);

    // Step 3 Data
    add('r_man_sondeID', sondeId);
    add('data_capture_date', dataCaptureDate);
    add('data_capture_time', dataCaptureTime);
    add('r_man_oxygen_conc', oxygenConcentration);
    add('r_man_oxygen_sat', oxygenSaturation);
    add('r_man_ph', ph);
    add('r_man_salinity', salinity);
    add('r_man_conductivity', electricalConductivity);
    add('r_man_temperature', temperature);
    add('r_man_tds', tds);
    add('r_man_turbidity', turbidity);
    add('r_man_tss', tss);
    add('r_man_battery_volt', batteryVoltage);

    // ADDED: Flowrate fields to API form data
    add('r_man_flowrate_method', flowrateMethod);
    add('r_man_flowrate_sd_height', flowrateSurfaceDrifterHeight);
    add('r_man_flowrate_sd_distance', flowrateSurfaceDrifterDistance);
    add('r_man_flowrate_sd_time_first', flowrateSurfaceDrifterTimeFirst);
    add('r_man_flowrate_sd_time_last', flowrateSurfaceDrifterTimeLast);
    add('r_man_flowrate_value', flowrateValue);


    // Additional data for display or logging
    add('first_sampler_name', firstSamplerName);
    add('r_man_station_code', selectedStation?['sampling_station_code']);
    add('r_man_station_name', selectedStation?['sampling_river']);


    return map;
  }

  /// Converts the image properties into a Map<String, File?> for the multipart API request.
  Map<String, File?> toApiImageFiles() {
    return {
      'r_man_background_station': backgroundStationImage,
      'r_man_upstream_river': upstreamRiverImage,
      'r_man_downstream_river': downstreamRiverImage,
      'r_man_sample_turbidity': sampleTurbidityImage,
      'r_man_optional_photo_01': optionalImage1,
      'r_man_optional_photo_02': optionalImage2,
      'r_man_optional_photo_03': optionalImage3,
      'r_man_optional_photo_04': optionalImage4,
    };
  }
}