// lib/models/air_collection_data.dart

import 'dart:io';
import 'dart:convert'; // Added for jsonEncode
import 'air_installation_data.dart';

class AirCollectionData {
  // Link to the original installation
  String? installationRefID;
  int? airManId; // The ID from the server database

  // Collection Info
  String? collectionDate;
  String? collectionTime;
  String? weather;
  double? temperature;
  String? powerFailure;

  // PM10 Readings
  double? pm10Flowrate;
  String? pm10FlowrateResult;
  String? pm10TotalTime;
  String? pm10TotalTimeResult;
  double? pm10Pressure;
  String? pm10PressureResult;
  double? pm10Vstd;

  // PM2.5 Readings
  double? pm25Flowrate;
  String? pm25FlowrateResult;
  String? pm25TotalTime;
  String? pm25TotalTimeResult;
  double? pm25Pressure;
  String? pm25PressureResult;
  double? pm25Vstd;

  // General
  String? remarks;
  int? collectionUserId;
  String? collectionUserName; // To hold the user's name for alerts
  String? status;

  // Image Files for Collection
  File? imageFront;
  File? imageBack;
  File? imageLeft;
  File? imageRight;
  File? imageChart;
  File? imageFilterPaper;
  File? optionalImage1;
  File? optionalImage2;
  File? optionalImage3;
  File? optionalImage4;
  String? optionalRemark1;
  String? optionalRemark2;
  String? optionalRemark3;
  String? optionalRemark4;

  AirCollectionData({
    this.installationRefID,
    this.airManId,
    this.collectionDate,
    this.collectionTime,
    this.weather,
    this.temperature,
    this.powerFailure,
    this.pm10Flowrate,
    this.pm10FlowrateResult,
    this.pm10TotalTime,
    this.pm10TotalTimeResult,
    this.pm10Pressure,
    this.pm10PressureResult,
    this.pm10Vstd,
    this.pm25Flowrate,
    this.pm25FlowrateResult,
    this.pm25TotalTime,
    this.pm25TotalTimeResult,
    this.pm25Pressure,
    this.pm25PressureResult,
    this.pm25Vstd,
    this.remarks,
    this.collectionUserId,
    this.collectionUserName,
    this.status,
    this.imageFront,
    this.imageBack,
    this.imageLeft,
    this.imageRight,
    this.imageChart,
    this.imageFilterPaper,
    this.optionalImage1,
    this.optionalImage2,
    this.optionalImage3,
    this.optionalImage4,
    this.optionalRemark1,
    this.optionalRemark2,
    this.optionalRemark3,
    this.optionalRemark4,
  });

  String generateCollectionTelegramAlert(AirInstallationData installationData, {required bool isDataOnly}) {
    final submissionType = isDataOnly ? "(Data Only)" : "(Data & Images)";
    final buffer = StringBuffer()
      ..writeln('✅ *Air Manual Collection $submissionType Submitted:*')
      ..writeln()
      ..writeln('*Station ID:* ${installationData.stationID ?? 'N/A'}')
      ..writeln('*Location:* ${installationData.locationName ?? 'N/A'}')
      ..writeln('*Collection Date:* ${collectionDate ?? 'N/A'} at ${collectionTime ?? 'N/A'}')
      ..writeln('*Submitted by User:* ${collectionUserName ?? 'N/A'}')
      ..writeln('*Status of Submission:* Successful');
    return buffer.toString();
  }

  factory AirCollectionData.fromMap(Map<String, dynamic> map) {
    File? fileFromPath(String? path) => path != null ? File(path) : null;

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

    return AirCollectionData(
      installationRefID: map['installationRefID'],
      airManId: map['air_man_id'],
      collectionDate: map['air_man_collection_date'],
      collectionTime: map['air_man_collection_time'],
      weather: map['air_man_collection_weather'],
      temperature: parseDouble(map['air_man_collection_temperature']),
      powerFailure: map['air_man_collection_power_failure'],
      pm10Flowrate: parseDouble(map['air_man_collection_pm10_flowrate']),
      pm10FlowrateResult: map['air_man_collection_pm10_flowrate_result'],
      pm10TotalTime: map['air_man_collection_pm10_total_time'],
      pm10TotalTimeResult: map['air_man_collection_total_time_result'],
      pm10Pressure: parseDouble(map['air_man_collection_pm10_pressure']),
      pm10PressureResult: map['air_man_collection_pm10_pressure_result'],
      pm10Vstd: parseDouble(map['air_man_collection_pm10_vstd']),
      pm25Flowrate: parseDouble(map['air_man_collection_pm25_flowrate']),
      pm25FlowrateResult: map['air_man_collection_pm25_flowrate_result'],
      pm25TotalTime: map['air_man_collection_pm25_total_time'],
      pm25TotalTimeResult: map['air_man_collection_pm25_total_time_result'],
      pm25Pressure: parseDouble(map['air_man_collection_pm25_pressure']),
      pm25PressureResult: map['air_man_collection_pm25_pressure_result'],
      pm25Vstd: parseDouble(map['air_man_collection_pm25_vstd']),
      remarks: map['air_man_collection_remarks'],
      collectionUserName: map['collectionUserName'],
      status: map['status'],
      optionalRemark1: map['optionalRemark1'],
      optionalRemark2: map['optionalRemark2'],
      optionalRemark3: map['optionalRemark3'],
      optionalRemark4: map['optionalRemark4'],
      imageFront: fileFromPath(map['imageFrontPath'] ?? map['imageFront']), // FIX: Check both path keys
      imageBack: fileFromPath(map['imageBackPath'] ?? map['imageBack']),     // FIX: Check both path keys
      imageLeft: fileFromPath(map['imageLeftPath'] ?? map['imageLeft']),     // FIX: Check both path keys
      imageRight: fileFromPath(map['imageRightPath'] ?? map['imageRight']),   // FIX: Check both path keys
      imageChart: fileFromPath(map['imageChartPath'] ?? map['imageChart']),
      imageFilterPaper: fileFromPath(map['imageFilterPaperPath'] ?? map['imageFilterPaper']),
      optionalImage1: fileFromPath(map['optionalImage1Path'] ?? map['optionalImage1']), // FIX: Check both path keys
      optionalImage2: fileFromPath(map['optionalImage2Path'] ?? map['optionalImage2']), // FIX: Check both path keys
      optionalImage3: fileFromPath(map['optionalImage3Path'] ?? map['optionalImage3']), // FIX: Check both path keys
      optionalImage4: fileFromPath(map['optionalImage4Path'] ?? map['optionalImage4']), // FIX: Check both path keys
    );
  }

  Map<String, dynamic> toMap() {
    return {
      'installationRefID': installationRefID,
      'air_man_id': airManId,
      'air_man_collection_date': collectionDate,
      'air_man_collection_time': collectionTime,
      'air_man_collection_weather': weather,
      'air_man_collection_temperature': temperature,
      'air_man_collection_power_failure': powerFailure,
      'air_man_collection_pm10_flowrate': pm10Flowrate,
      'air_man_collection_pm10_flowrate_result': pm10FlowrateResult,
      'air_man_collection_pm10_total_time': pm10TotalTime,
      'air_man_collection_total_time_result': pm10TotalTimeResult,
      'air_man_collection_pm10_pressure': pm10Pressure,
      'air_man_collection_pm10_pressure_result': pm10PressureResult,
      'air_man_collection_pm10_vstd': pm10Vstd,
      'air_man_collection_pm25_flowrate': pm25Flowrate,
      'air_man_collection_pm25_flowrate_result': pm25FlowrateResult,
      'air_man_collection_pm25_total_time': pm25TotalTime,
      'air_man_collection_pm25_total_time_result': pm25TotalTimeResult,
      'air_man_collection_pm25_pressure': pm25Pressure,
      'air_man_collection_pm25_pressure_result': pm25PressureResult,
      'air_man_collection_pm25_vstd': pm25Vstd,
      'air_man_collection_remarks': remarks,
      'collectionUserName': collectionUserName,
      'status': status,
      'optionalRemark1': optionalRemark1,
      'optionalRemark2': optionalRemark2,
      'optionalRemark3': optionalRemark3,
      'optionalRemark4': optionalRemark4,
      'imageFront': imageFront?.path, // Store path for log
      'imageBack': imageBack?.path,   // Store path for log
      'imageLeft': imageLeft?.path,   // Store path for log
      'imageRight': imageRight?.path, // Store path for log
      'imageChart': imageChart?.path,
      'imageFilterPaper': imageFilterPaper?.path,
      'optionalImage1': optionalImage1?.path,
      'optionalImage2': optionalImage2?.path,
      'optionalImage3': optionalImage3?.path,
      'optionalImage4': optionalImage4?.path,
    };
  }

  Map<String, dynamic> toJson() {
    return {
      'air_man_id': airManId?.toString(),
      'air_man_collection_user_id': collectionUserId?.toString(),
      'air_man_collection_date': collectionDate,
      'air_man_collection_time': collectionTime,
      'air_man_collection_weather': weather,
      'air_man_collection_temperature': temperature?.toString(),
      'air_man_collection_power_failure': powerFailure,
      'air_man_collection_pm10_flowrate': pm10Flowrate?.toString(),
      'air_man_collection_pm10_flowrate_result': pm10FlowrateResult,
      'air_man_collection_pm10_total_time': pm10TotalTime,
      'air_man_collection_pm10_total_time_result': pm10TotalTimeResult,
      'air_man_collection_pm10_pressure': pm10Pressure?.toString(),
      'air_man_collection_pm10_pressure_result': pm10PressureResult,
      'air_man_collection_pm10_vstd': pm10Vstd?.toString(),
      'air_man_collection_pm25_flowrate': pm25Flowrate?.toString(),
      'air_man_collection_pm25_flowrate_result': pm25FlowrateResult,
      'air_man_collection_pm25_total_time': pm25TotalTime,
      'air_man_collection_pm25_total_time_result': pm25TotalTimeResult,
      'air_man_collection_pm25_pressure': pm25Pressure?.toString(),
      'air_man_collection_pm25_pressure_result': pm25PressureResult,
      'air_man_collection_pm25_vstd': pm25Vstd?.toString(),
      'air_man_collection_remarks': remarks,
      'air_man_collection_image_optional_01_remarks': optionalRemark1,
      'air_man_collection_image_optional_02_remarks': optionalRemark2,
      'air_man_collection_image_optional_03_remarks': optionalRemark3,
      'air_man_collection_image_optional_04_remarks': optionalRemark4,
    };
  }

  Map<String, File> getImagesForUpload() {
    final Map<String, File> files = {};
    if (imageFront != null) files['front'] = imageFront!;
    if (imageBack != null) files['back'] = imageBack!;
    if (imageLeft != null) files['left'] = imageLeft!;
    if (imageRight != null) files['right'] = imageRight!;
    if (imageChart != null) files['chart'] = imageChart!;
    if (imageFilterPaper != null) files['filter_paper'] = imageFilterPaper!;
    if (optionalImage1 != null) files['optional_01'] = optionalImage1!;
    if (optionalImage2 != null) files['optional_02'] = optionalImage2!;
    if (optionalImage3 != null) files['optional_03'] = optionalImage3!;
    if (optionalImage4 != null) files['optional_04'] = optionalImage4!;
    return files;
  }
}