// lib/models/river_manual_triennial_sampling_data.dart

import 'dart:io';
import 'dart:convert';

/// Data model for the River Manual Triennial Sampling form.
class RiverManualTriennialSamplingData {
  // --- Step 1: Sampling & Station Info ---
  String? firstSamplerName;
  int? firstSamplerUserId;
  Map<String, dynamic>? secondSampler;
  String? samplingDate;
  String? samplingTime;
  String? samplingType;
  String? sampleIdCode;

  String? selectedStateName;
  Map<String, dynamic>? selectedStation; // Triennial stations don't have categories

  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 (Mirrors River In-Situ for now) ---
  String? sondeId;
  String? dataCaptureDate;
  String? dataCaptureTime;
  double? oxygenConcentration;
  double? oxygenSaturation;
  double? ph;
  double? salinity;
  double? electricalConductivity;
  double? temperature;
  double? tds;
  double? turbidity;
  double? ammonia; // Replaced tss with ammonia
  double? batteryVoltage;

  String? flowrateMethod;
  double? flowrateSurfaceDrifterHeight;
  double? flowrateSurfaceDrifterDistance;
  String? flowrateSurfaceDrifterTimeFirst;
  String? flowrateSurfaceDrifterTimeLast;
  double? flowrateValue;

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

  RiverManualTriennialSamplingData({
    this.samplingDate,
    this.samplingTime,
    this.samplingType = 'Triennial', // Default for this form
  });

  factory RiverManualTriennialSamplingData.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;
    }

    int? intFromJson(dynamic value) {
      if (value is int) return value;
      if (value is String) return int.tryParse(value);
      return null;
    }

    return RiverManualTriennialSamplingData()
      ..firstSamplerName = json['firstSamplerName'] ?? json['first_sampler_name']
      ..firstSamplerUserId = intFromJson(json['firstSamplerUserId'] ?? json['first_sampler_user_id'])
      ..secondSampler = json['secondSampler']
      ..samplingDate = json['samplingDate'] ?? json['r_tri_date']
      ..samplingTime = json['samplingTime'] ?? json['r_tri_time']
      ..samplingType = json['samplingType'] ?? json['r_tri_type']
      ..sampleIdCode = json['sampleIdCode'] ?? json['r_tri_sample_id_code']
      ..selectedStateName = json['selectedStateName']
      ..selectedStation = json['selectedStation']
      ..stationLatitude = json['stationLatitude']
      ..stationLongitude = json['stationLongitude']
      ..currentLatitude = (json['currentLatitude'] ?? json['r_tri_current_latitude'])?.toString()
      ..currentLongitude = (json['currentLongitude'] ?? json['r_tri_current_longitude'])?.toString()
      ..distanceDifferenceInKm = doubleFromJson(json['distanceDifferenceInKm'] ?? json['r_tri_distance_difference'])
      ..distanceDifferenceRemarks = json['distanceDifferenceRemarks'] ?? json['r_tri_distance_difference_remarks']
      ..weather = json['weather'] ?? json['r_tri_weather']
      ..eventRemarks = json['eventRemarks'] ?? json['r_tri_event_remark']
      ..labRemarks = json['labRemarks'] ?? json['r_tri_lab_remark']
      ..sondeId = json['sondeId'] ?? json['r_tri_sondeID']
      ..dataCaptureDate = json['dataCaptureDate'] ?? json['data_capture_date']
      ..dataCaptureTime = json['dataCaptureTime'] ?? json['data_capture_time']
      ..oxygenConcentration = doubleFromJson(json['oxygenConcentration'] ?? json['r_tri_oxygen_conc'])
      ..oxygenSaturation = doubleFromJson(json['oxygenSaturation'] ?? json['r_tri_oxygen_sat'])
      ..ph = doubleFromJson(json['ph'] ?? json['r_tri_ph'])
      ..salinity = doubleFromJson(json['salinity'] ?? json['r_tri_salinity'])
      ..electricalConductivity = doubleFromJson(json['electricalConductivity'] ?? json['r_tri_conductivity'])
      ..temperature = doubleFromJson(json['temperature'] ?? json['r_tri_temperature'])
      ..tds = doubleFromJson(json['tds'] ?? json['r_tri_tds'])
      ..turbidity = doubleFromJson(json['turbidity'] ?? json['r_tri_turbidity'])
      ..ammonia = doubleFromJson(json['ammonia'] ?? json['r_tri_ammonia'])
      ..batteryVoltage = doubleFromJson(json['batteryVoltage'] ?? json['r_tri_battery_volt'])
      ..optionalRemark1 = json['optionalRemark1'] ?? json['r_tri_optional_photo_01_remarks']
      ..optionalRemark2 = json['optionalRemark2'] ?? json['r_tri_optional_photo_02_remarks']
      ..optionalRemark3 = json['optionalRemark3'] ?? json['r_tri_optional_photo_03_remarks']
      ..optionalRemark4 = json['optionalRemark4'] ?? json['r_tri_optional_photo_04_remarks']
      ..backgroundStationImage = fileFromJson(json['backgroundStationImage'] ?? json['r_tri_background_station'])
      ..upstreamRiverImage = fileFromJson(json['upstreamRiverImage'] ?? json['r_tri_upstream_river'])
      ..downstreamRiverImage = fileFromJson(json['downstreamRiverImage'] ?? json['r_tri_downstream_river'])
      ..sampleTurbidityImage = fileFromJson(json['sampleTurbidityImage'] ?? json['r_tri_sample_turbidity'])
      ..optionalImage1 = fileFromJson(json['optionalImage1'] ?? json['r_tri_optional_photo_01'])
      ..optionalImage2 = fileFromJson(json['optionalImage2'] ?? json['r_tri_optional_photo_02'])
      ..optionalImage3 = fileFromJson(json['optionalImage3'] ?? json['r_tri_optional_photo_03'])
      ..optionalImage4 = fileFromJson(json['optionalImage4'] ?? json['r_tri_optional_photo_04'])
      ..flowrateMethod = json['flowrateMethod'] ?? json['r_tri_flowrate_method']
      ..flowrateSurfaceDrifterHeight = doubleFromJson(json['flowrateSurfaceDrifterHeight'] ?? json['r_tri_flowrate_sd_height'])
      ..flowrateSurfaceDrifterDistance = doubleFromJson(json['flowrateSurfaceDrifterDistance'] ?? json['r_tri_flowrate_sd_distance'])
      ..flowrateSurfaceDrifterTimeFirst = json['flowrateSurfaceDrifterTimeFirst'] ?? json['r_tri_flowrate_sd_time_first']
      ..flowrateSurfaceDrifterTimeLast = json['flowrateSurfaceDrifterTimeLast'] ?? json['r_tri_flowrate_sd_time_last']
      ..flowrateValue = doubleFromJson(json['flowrateValue'] ?? json['r_tri_flowrate_value'])
      ..submissionStatus = json['submissionStatus']
      ..submissionMessage = json['submissionMessage']
      ..reportId = json['reportId']?.toString();
  }


  /// 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) {
        String stringValue;
        if (value is double) {
          if (value == -999.0) {
            stringValue = '-999';
          } else {
            stringValue = value.toStringAsFixed(5);
          }
        } else {
          stringValue = value.toString();
        }
        if (stringValue.isNotEmpty) {
          map[key] = stringValue;
        }
      }
    }

    // Step 1 Data
    add('first_sampler_user_id', firstSamplerUserId);
    add('r_tri_second_sampler_id', secondSampler?['user_id']);
    add('r_tri_date', samplingDate);
    add('r_tri_time', samplingTime);
    add('r_tri_type', samplingType);
    add('r_tri_sample_id_code', sampleIdCode);
    add('station_id', selectedStation?['station_id']);
    add('r_tri_current_latitude', currentLatitude);
    add('r_tri_current_longitude', currentLongitude);
    add('r_tri_distance_difference', distanceDifferenceInKm);
    add('r_tri_distance_difference_remarks', distanceDifferenceRemarks);

    // Step 2 Data
    add('r_tri_weather', weather);
    add('r_tri_event_remark', eventRemarks);
    add('r_tri_lab_remark', labRemarks);

    // Step 4 Data
    add('r_tri_optional_photo_01_remarks', optionalRemark1);
    add('r_tri_optional_photo_02_remarks', optionalRemark2);
    add('r_tri_optional_photo_03_remarks', optionalRemark3);
    add('r_tri_optional_photo_04_remarks', optionalRemark4);

    // Step 3 Data
    add('r_tri_sondeID', sondeId);
    add('data_capture_date', dataCaptureDate);
    add('data_capture_time', dataCaptureTime);
    add('r_tri_oxygen_conc', oxygenConcentration);
    add('r_tri_oxygen_sat', oxygenSaturation);
    add('r_tri_ph', ph);
    add('r_tri_salinity', salinity);
    add('r_tri_conductivity', electricalConductivity);
    add('r_tri_temperature', temperature);
    add('r_tri_tds', tds);
    add('r_tri_turbidity', turbidity);
    add('r_tri_ammonia', ammonia);
    add('r_tri_battery_volt', batteryVoltage);
    add('r_tri_flowrate_method', flowrateMethod);
    add('r_tri_flowrate_sd_height', flowrateSurfaceDrifterHeight);
    add('r_tri_flowrate_sd_distance', flowrateSurfaceDrifterDistance);
    add('r_tri_flowrate_sd_time_first', flowrateSurfaceDrifterTimeFirst);
    add('r_tri_flowrate_sd_time_last', flowrateSurfaceDrifterTimeLast);
    add('r_tri_flowrate_value', flowrateValue);

    // Additional data for display or logging
    add('first_sampler_name', firstSamplerName);
    add('r_tri_station_code', selectedStation?['sampling_station_code']);
    add('r_tri_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_tri_background_station': backgroundStationImage,
      'r_tri_upstream_river': upstreamRiverImage,
      'r_tri_downstream_river': downstreamRiverImage,
      'r_tri_sample_turbidity': sampleTurbidityImage,
      'r_tri_optional_photo_01': optionalImage1,
      'r_tri_optional_photo_02': optionalImage2,
      'r_tri_optional_photo_03': optionalImage3,
      'r_tri_optional_photo_04': optionalImage4,
    };
  }

  /// Converts the data model into a Map suitable for saving to local storage or DB log.
  Map<String, dynamic> toMap() {
    return {
      'firstSamplerName': firstSamplerName,
      'firstSamplerUserId': firstSamplerUserId,
      'secondSampler': secondSampler,
      'samplingDate': samplingDate,
      'samplingTime': samplingTime,
      'samplingType': samplingType,
      'sampleIdCode': sampleIdCode,
      'selectedStateName': selectedStateName,
      'selectedStation': selectedStation,
      'stationLatitude': stationLatitude,
      'stationLongitude': stationLongitude,
      'currentLatitude': currentLatitude,
      'currentLongitude': currentLongitude,
      'distanceDifferenceInKm': distanceDifferenceInKm,
      'distanceDifferenceRemarks': distanceDifferenceRemarks,
      'weather': weather,
      'eventRemarks': eventRemarks,
      'labRemarks': labRemarks,
      'backgroundStationImage': backgroundStationImage?.path,
      'upstreamRiverImage': upstreamRiverImage?.path,
      'downstreamRiverImage': downstreamRiverImage?.path,
      'sampleTurbidityImage': sampleTurbidityImage?.path,
      'optionalImage1': optionalImage1?.path,
      'optionalRemark1': optionalRemark1,
      'optionalImage2': optionalImage2?.path,
      'optionalRemark2': optionalRemark2,
      'optionalImage3': optionalImage3?.path,
      'optionalRemark3': optionalRemark3,
      'optionalImage4': optionalImage4?.path,
      'optionalRemark4': optionalRemark4,
      'sondeId': sondeId,
      'dataCaptureDate': dataCaptureDate,
      'dataCaptureTime': dataCaptureTime,
      'oxygenConcentration': oxygenConcentration,
      'oxygenSaturation': oxygenSaturation,
      'ph': ph,
      'salinity': salinity,
      'electricalConductivity': electricalConductivity,
      'temperature': temperature,
      'tds': tds,
      'turbidity': turbidity,
      'ammonia': ammonia,
      'batteryVoltage': batteryVoltage,
      'flowrateMethod': flowrateMethod,
      'flowrateSurfaceDrifterHeight': flowrateSurfaceDrifterHeight,
      'flowrateSurfaceDrifterDistance': flowrateSurfaceDrifterDistance,
      'flowrateSurfaceDrifterTimeFirst': flowrateSurfaceDrifterTimeFirst,
      'flowrateSurfaceDrifterTimeLast': flowrateSurfaceDrifterTimeLast,
      'flowrateValue': flowrateValue,
      'submissionStatus': submissionStatus,
      'submissionMessage': submissionMessage,
      'reportId': reportId,
    };
  }

  /// Creates a single JSON object with all submission data.
  /// Every value is explicitly converted to a String for the API.
  String toDbJson() {
    final data = {
      'battery_cap': (batteryVoltage == null || batteryVoltage == -999.0) ? "NULL" : batteryVoltage.toString(),
      'device_name': (sondeId ?? "").toString(),
      'sampling_type': (samplingType ?? "").toString(),
      'report_id': (reportId ?? "").toString(),
      'sampler_2ndname': (secondSampler?['first_name'] ?? "").toString(),
      'sample_state': (selectedStateName ?? "").toString(),
      'station_id': (selectedStation?['sampling_station_code'] ?? "").toString(),
      'tech_id': (firstSamplerUserId ?? "NULL").toString(),
      'tech_phonenum': "NULL",
      'tech_name': (firstSamplerName ?? "").toString(),
      'latitude': (stationLatitude ?? "").toString(),
      'longitude': (stationLongitude ?? "").toString(),
      'record_dt': '$samplingDate $samplingTime',
      'do_mgl': (oxygenConcentration == null || oxygenConcentration == -999.0) ? "NULL" : oxygenConcentration.toString(),
      'do_sat': (oxygenSaturation == null || oxygenSaturation == -999.0) ? "NULL" : oxygenSaturation.toString(),
      'ph': (ph == null || ph == -999.0) ? "NULL" : ph.toString(),
      'salinity': (salinity == null || salinity == -999.0) ? "NULL" : salinity.toString(),
      'temperature': (temperature == null || temperature == -999.0) ? "NULL" : temperature.toString(),
      'turbidity': (turbidity == null || turbidity == -999.0) ? "NULL" : turbidity.toString(),
      'tds': (tds == null || tds == -999.0) ? "NULL" : tds.toString(),
      'electric_conductivity': (electricalConductivity == null || electricalConductivity == -999.0) ? "NULL" : electricalConductivity.toString(),
      'tss': (ammonia == null || ammonia == -999.0) ? "NULL" : ammonia.toString(),
      'flowrate': (flowrateValue == null || flowrateValue == -999.0) ? "NULL" : flowrateValue.toString(),
      'odour': '',
      'floatable': '',
      'sample_id': (sampleIdCode ?? "").toString(),
      'weather': (weather ?? "").toString(),
      'remarks_event': (eventRemarks ?? "").toString(),
      'remarks_lab': (labRemarks ?? "").toString(),
      'tarball': "No",
      'tide_lvl': "",
      'sea_cond': "",
    };
    return jsonEncode(data);
  }

  /// Creates a JSON object for basic form info.
  /// Every value is explicitly converted to a String.
  String toBasicFormJson() {
    final data = {
      'tech_name': (firstSamplerName ?? "").toString(),
      'sampler_2ndname': (secondSampler?['first_name'] ?? "").toString(),
      'sample_date': (samplingDate ?? "").toString(),
      'sample_time': (samplingTime ?? "").toString(),
      'sampling_type': (samplingType ?? "").toString(),
      'sample_state': (selectedStateName ?? "").toString(),
      'station_id': (selectedStation?['sampling_station_code'] ?? "").toString(),
      'station_latitude': (stationLatitude ?? "").toString(),
      'station_longitude': (stationLongitude ?? "").toString(),
      'latitude': (currentLatitude ?? "").toString(),
      'longitude': (currentLongitude ?? "").toString(),
      'sample_id': (sampleIdCode ?? "").toString(),
    };

    return jsonEncode(data);
  }

  /// Creates a JSON object for sensor readings.
  /// Every value is explicitly converted to a String.
  String toReadingJson() {
    final data = {
      'do_mgl': (oxygenConcentration == null || oxygenConcentration == -999.0) ? "NULL" : oxygenConcentration.toString(),
      'do_sat': (oxygenSaturation == null || oxygenSaturation == -999.0) ? "NULL" : oxygenSaturation.toString(),
      'ph': (ph == null || ph == -999.0) ? "NULL" : ph.toString(),
      'salinity': (salinity == null || salinity == -999.0) ? "NULL" : salinity.toString(),
      'temperature': (temperature == null || temperature == -999.0) ? "NULL" : temperature.toString(),
      'turbidity': (turbidity == null || turbidity == -999.0) ? "NULL" : turbidity.toString(),
      'tds': (tds == null || tds == -999.0) ? "NULL" : tds.toString(),
      'electric_conductivity': (electricalConductivity == null || electricalConductivity == -999.0) ? "NULL" : electricalConductivity.toString(),
      'tss': (ammonia == null || ammonia == -999.0) ? "NULL" : ammonia.toString(),
      'flowrate': (flowrateValue == null || flowrateValue == -999.0) ? "NULL" : flowrateValue.toString(),
      'date_sampling_reading': (dataCaptureDate ?? "").toString(),
      'time_sampling_reading': (dataCaptureTime ?? "").toString(),
    };

    return jsonEncode(data);
  }

  /// Creates a JSON object for manual info.
  /// Every value is explicitly converted to a String.
  String toManualInfoJson() {
    final data = {
      'weather': (weather ?? "").toString(),
      'remarks_event': (eventRemarks ?? "").toString(),
      'remarks_lab': (labRemarks ?? "").toString(),
    };
    return jsonEncode(data);
  }
}