// lib/models/air_installation_data.dart

import 'dart:io';
import 'dart:convert'; // Added for jsonEncode
import 'air_collection_data.dart'; // Import the collection data model

class AirInstallationData {
  String? refID;
  int? airManId; // The ID from the server database
  String? samplingDate;
  int? clientId;
  String? installationDate;
  String? installationTime;
  String? stateID;
  String? locationName;
  String? stationID;
  String? region;
  String? weather;
  String? temp;
  bool powerFailure;
  String? pm10FilterId;
  String? pm25FilterId;
  String? remark;
  int? installationUserId;
  String? installationUserName; // To hold the user's name for alerts

  File? imageFront;
  File? imageBack;
  File? imageLeft;
  File? imageRight;

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

  String? imageFrontPath;
  String? imageBackPath;
  String? imageLeftPath;
  String? imageRightPath;
  String? optionalImage1Path;
  String? optionalImage2Path;
  String? optionalImage3Path;
  String? optionalImage4Path;

  String? status;

  AirCollectionData? collectionData;

  AirInstallationData({
    this.refID,
    this.airManId,
    this.samplingDate,
    this.clientId,
    this.installationDate,
    this.installationTime,
    this.stateID,
    this.locationName,
    this.stationID,
    this.region,
    this.weather,
    this.temp,
    this.powerFailure = false,
    this.pm10FilterId,
    this.pm25FilterId,
    this.remark,
    this.installationUserId,
    this.installationUserName,
    this.imageFront,
    this.imageBack,
    this.imageLeft,
    this.imageRight,
    this.optionalImage1,
    this.optionalImage2,
    this.optionalImage3,
    this.optionalImage4,
    this.optionalRemark1,
    this.optionalRemark2,
    this.optionalRemark3,
    this.optionalRemark4,
    this.imageFrontPath,
    this.imageBackPath,
    this.imageLeftPath,
    this.imageRightPath,
    this.optionalImage1Path,
    this.optionalImage2Path,
    this.optionalImage3Path,
    this.optionalImage4Path,
    this.status,
    this.collectionData,
  });

  String generateInstallationTelegramAlert({required bool isDataOnly}) {
    final submissionType = isDataOnly ? "(Data Only)" : "(Data & Images)";
    final buffer = StringBuffer()
      ..writeln('✅ *Air Manual Installation $submissionType Submitted:*')
      ..writeln()
      ..writeln('*Station ID:* ${stationID ?? 'N/A'}')
      ..writeln('*Location:* ${locationName ?? 'N/A'}')
      ..writeln('*Installation Date:* ${installationDate ?? 'N/A'} at ${installationTime ?? 'N/A'}')
      ..writeln('*Submitted by User:* ${installationUserName ?? 'N/A'}')
      ..writeln('*Status of Submission:* Successful');
    return buffer.toString();
  }

  Map<String, dynamic> toMap() {
    return {
      'refID': refID,
      'air_man_id': airManId,
      'samplingDate': samplingDate,
      'clientId': clientId,
      'installationDate': installationDate,
      'installationTime': installationTime,
      'stateID': stateID,
      'locationName': locationName,
      'stationID': stationID,
      'region': region,
      'weather': weather,
      'temp': temp,
      'powerFailure': powerFailure,
      'pm10FilterId': pm10FilterId,
      'pm25FilterId': pm25FilterId,
      'remark': remark,
      'installationUserId': installationUserId,
      'installationUserName': installationUserName,
      '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
      'optionalImage1': optionalImage1?.path, // Store path for log
      'optionalImage2': optionalImage2?.path, // Store path for log
      'optionalImage3': optionalImage3?.path, // Store path for log
      'optionalImage4': optionalImage4?.path, // Store path for log
      'collectionData': collectionData?.toMap(),
    };
  }

  factory AirInstallationData.fromJson(Map<String, dynamic> json) {
    File? fileFromPath(String? path) => (path != null && path.isNotEmpty) ? File(path) : null;

    return AirInstallationData(
      refID: json['refID'],
      airManId: json['air_man_id'],
      samplingDate: json['samplingDate'],
      clientId: json['clientId'],
      installationDate: json['installationDate'],
      installationTime: json['installationTime'],
      stateID: json['stateID'],
      locationName: json['locationName'],
      stationID: json['stationID'],
      region: json['region'],
      weather: json['weather'],
      temp: json['temp'],
      powerFailure: json['powerFailure'] ?? false,
      pm10FilterId: json['pm10FilterId'],
      pm25FilterId: json['pm25FilterId'],
      remark: json['remark'],
      installationUserId: json['installationUserId'],
      installationUserName: json['installationUserName'],
      status: json['status'],
      imageFront: fileFromPath(json['imageFrontPath'] ?? json['imageFront']), // FIX: Check both path keys
      imageBack: fileFromPath(json['imageBackPath'] ?? json['imageBack']),     // FIX: Check both path keys
      imageLeft: fileFromPath(json['imageLeftPath'] ?? json['imageLeft']),     // FIX: Check both path keys
      imageRight: fileFromPath(json['imageRightPath'] ?? json['imageRight']),   // FIX: Check both path keys
      optionalImage1: fileFromPath(json['optionalImage1Path'] ?? json['optionalImage1']), // FIX: Check both path keys
      optionalImage2: fileFromPath(json['optionalImage2Path'] ?? json['optionalImage2']), // FIX: Check both path keys
      optionalImage3: fileFromPath(json['optionalImage3Path'] ?? json['optionalImage3']), // FIX: Check both path keys
      optionalImage4: fileFromPath(json['optionalImage4Path'] ?? json['optionalImage4']), // FIX: Check both path keys
      optionalRemark1: json['optionalRemark1'],
      optionalRemark2: json['optionalRemark2'],
      optionalRemark3: json['optionalRemark3'],
      optionalRemark4: json['optionalRemark4'],
      collectionData: json['collectionData'] != null && json['collectionData'] is Map
          ? AirCollectionData.fromMap(json['collectionData'])
          : null,
    );
  }

  Map<String, dynamic> toJsonForApi() {
    return {
      'air_man_station_code': stationID,
      'air_man_sampling_date': samplingDate,
      'air_man_client_id': clientId?.toString(),
      'air_man_installation_date': installationDate,
      'air_man_installation_time': installationTime,
      'air_man_installation_weather': weather,
      'air_man_installation_temperature': temp,
      'air_man_installation_power_failure': powerFailure ? 'Yes' : 'No',
      'air_man_installation_pm10_filter_id': pm10FilterId,
      'air_man_installation_pm25_filter_id': pm25FilterId,
      'air_man_installation_remarks': remark,
      'air_man_installation_image_optional_01_remarks': optionalRemark1,
      'air_man_installation_image_optional_02_remarks': optionalRemark2,
      'air_man_installation_image_optional_03_remarks': optionalRemark3,
      'air_man_installation_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 (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;
  }

  // --- ADDED: Methods to format data for FTP submission as separate JSON files ---

  /// Creates a single JSON object with all submission data, mimicking 'db.json'
  Map<String, dynamic> toDbJson() {
    final data = {
      'refID': refID,
      'air_man_id': airManId,
      'samplingDate': samplingDate,
      'clientId': clientId,
      'installationDate': installationDate,
      'installationTime': installationTime,
      'stateID': stateID,
      'locationName': locationName,
      'stationID': stationID,
      'region': region,
      'weather': weather,
      'temp': temp,
      'powerFailure': powerFailure,
      'pm10FilterId': pm10FilterId,
      'pm25FilterId': pm25FilterId,
      'remark': remark,
      'installationUserId': installationUserId,
      'installationUserName': installationUserName,
      'status': status,
      'optionalRemark1': optionalRemark1,
      'optionalRemark2': optionalRemark2,
      'optionalRemark3': optionalRemark3,
      'optionalRemark4': optionalRemark4,
      'collectionData': collectionData?.toMap(),
    };
    return data;
  }

  /// Creates a JSON object for basic installation form info, mimicking 'installation_form.json'.
  Map<String, dynamic> toInstallationFormJson() {
    return {
      'air_man_station_code': stationID,
      'air_man_sampling_date': samplingDate,
      'air_man_client_id': clientId,
      'air_man_installation_date': installationDate,
      'air_man_installation_time': installationTime,
      'air_man_installation_weather': weather,
      'air_man_installation_temperature': temp,
      'air_man_installation_power_failure': powerFailure ? 'Yes' : 'No',
      'air_man_installation_pm10_filter_id': pm10FilterId,
      'air_man_installation_pm25_filter_id': pm25FilterId,
      'air_man_installation_remarks': remark,
      'air_man_installation_image_optional_01_remarks': optionalRemark1,
      'air_man_installation_image_optional_02_remarks': optionalRemark2,
      'air_man_installation_image_optional_03_remarks': optionalRemark3,
      'air_man_installation_image_optional_04_remarks': optionalRemark4,
    };
  }

  /// Creates a JSON object for manual info, mimicking a generic 'manual_info.json' file.
  Map<String, dynamic> toManualInfoJson() {
    return {
      'weather': weather,
      'remarks_event': remark,
      'remarks_lab': null,
    };
  }
}