// lib/models/marine_manual_equipment_maintenance_data.dart

import 'dart:convert';

class MarineManualEquipmentMaintenanceData {
  int? conductedByUserId;
  String? conductedByUserName;
  String? maintenanceDate;
  String? lastMaintenanceDate;
  String? scheduleMaintenance;
  bool isReplacement = false;

  String? timeStart;
  String? timeEnd;
  String? location;

  // Part 1 - YSI
  Map<String, bool> ysiSondeChecks = {};
  String? ysiSondeComments;
  Map<String, Map<String, bool>> ysiSensorChecks = {};
  String? ysiSensorComments;
  Map<String, Map<String, String>> ysiReplacements = {};

  // Part 2 - Van Dorn Sampler
  Map<String, Map<String, bool>> vanDornChecks = {};
  String? vanDornComments;
  String? vanDornCurrentSerial;
  String? vanDornNewSerial;
  Map<String, Map<String, String>> vanDornReplacements = {};

  String? submissionStatus;
  String? submissionMessage;
  String? reportId;


  // Constructor to initialize maps
  MarineManualEquipmentMaintenanceData() {
    // Init Part 1 Sonde Checks
    ysiSondeChecks = {'Inspect': false, 'Clean': false};

    // Init Part 1 Sensor Checks
    [
      'pH',
      'Conductivity',
      'Turbidity',
      'Dissolved Oxygen',
    ].forEach((item) => ysiSensorChecks[item] = {'Inspect': false, 'Clean': false});

    // Init Part 1 Replacements
    [
      'YSI EXO 2 Multiparameter Sonde',
      'pH',
      'Conductivity',
      'Turbidity',
      'Dissolved Oxygen',
    ].forEach((item) =>
    ysiReplacements[item] = {'Current Serial': '', 'New Serial': ''});

    // Init Part 2 Van Dorn Checks
    vanDornChecks['Inside body, outside body & outlet valves cleaning'] = {'Inspect': false, 'Clean': false};
    vanDornChecks['Check cable assembly & tubing assembly'] = {'Inspect': false};
    vanDornChecks['Check messenger and rope'] = {'Inspect': false};


    // Init Part 2 Van Dorn Replacements
    [
      'End seals with air / drain valve',
      'Tubing Assembly',
      'Cable Assembly',
      'Main Tube Transparent',
    ].forEach((item) =>
    vanDornReplacements[item] = {'Last Date': '', 'New Date': ''});
  }

  /// Creates a JSON object for offline database storage.
  Map<String, dynamic> toDbJson() {
    return {
      'conductedByUserId': conductedByUserId,
      'conductedByUserName': conductedByUserName,
      'maintenanceDate': maintenanceDate,
      'lastMaintenanceDate': lastMaintenanceDate,
      'scheduleMaintenance': scheduleMaintenance,
      'isReplacement': isReplacement,
      'timeStart': timeStart,
      'timeEnd': timeEnd,
      'location': location,
      'ysiSondeChecks': ysiSondeChecks,
      'ysiSondeComments': ysiSondeComments,
      'ysiSensorChecks': ysiSensorChecks,
      'ysiSensorComments': ysiSensorComments,
      'ysiReplacements': ysiReplacements,
      'vanDornChecks': vanDornChecks,
      'vanDornComments': vanDornComments,
      'vanDornCurrentSerial': vanDornCurrentSerial,
      'vanDornNewSerial': vanDornNewSerial,
      'vanDornReplacements': vanDornReplacements,
      'submissionStatus': submissionStatus,
      'submissionMessage': submissionMessage,
      'reportId': reportId,
    };
  }

  // MODIFIED: This method now builds the complex nested structure the PHP controller expects.
  Map<String, dynamic> toApiFormData() {

    // 1. YSI Sensor Checks List
    List<Map<String, dynamic>> ysiSensorChecksList = [];
    ysiSensorChecks.forEach((sensorName, checks) {
      ysiSensorChecksList.add({
        'sensor_name': sensorName,
        'inspect_checked': checks['Inspect'] ?? false,
        'clean_checked': checks['Clean'] ?? false,
      });
    });

    // 2. YSI Replacements List
    List<Map<String, dynamic>> ysiReplacementsList = [];
    ysiReplacements.forEach((itemName, serials) {
      ysiReplacementsList.add({
        'item_name': itemName,
        'current_serial': serials['Current Serial'] ?? '',
        'new_serial': serials['New Serial'] ?? '',
      });
    });

    // 3. Van Dorn Checks List
    List<Map<String, dynamic>> vanDornChecksList = [];
    vanDornChecks.forEach((scopeName, checks) {
      vanDornChecksList.add({
        'scope_name': scopeName,
        'inspect_checked': checks['Inspect'] ?? false,
        'clean_checked': checks.containsKey('Clean') ? (checks['Clean'] ?? false) : null, // Handle items with no clean check
      });
    });

    // 4. Van Dorn Replacements List
    List<Map<String, dynamic>> vanDornReplacementsList = [];
    vanDornReplacements.forEach((partName, dates) {
      vanDornReplacementsList.add({
        'part_name': partName,
        // Send null if string is empty, which PHP controller expects
        'last_replacement_date': dates['Last Date']?.isEmpty ?? true ? null : dates['Last Date'],
        'new_replacement_date': dates['New Date']?.isEmpty ?? true ? null : dates['New Date'],
      });
    });

    // 5. Build final payload matching the controller
    return {
      'conducted_by_user_id': conductedByUserId.toString(),
      'maintenance_date': maintenanceDate,
      'last_maintenance_date': lastMaintenanceDate?.isEmpty ?? true ? null : lastMaintenanceDate,
      'schedule_maintenance': scheduleMaintenance,
      'is_replacement': isReplacement,
      'time_start': timeStart?.isEmpty ?? true ? null : timeStart,
      'time_end': timeEnd?.isEmpty ?? true ? null : timeEnd,
      'location': location,

      // YSI Sonde main checks
      'ysi_sonde_inspect': ysiSondeChecks['Inspect'] ?? false,
      'ysi_sonde_clean': ysiSondeChecks['Clean'] ?? false,

      'ysi_sonde_comments': ysiSondeComments,
      'ysi_sensor_comments': ysiSensorComments,
      'van_dorn_comments': vanDornComments,
      'van_dorn_current_serial': vanDornCurrentSerial,
      'van_dorn_new_serial': vanDornNewSerial,

      // The formatted lists
      'ysi_sensor_checks': ysiSensorChecksList,
      'ysi_replacements': ysiReplacementsList,
      'van_dorn_checks': vanDornChecksList,
      'van_dorn_replacements': vanDornReplacementsList,
    };
  }

  // --- START: ADDED TELEGRAM METHOD ---
  String generateTelegramAlertMessage() {
    final buffer = StringBuffer()
      ..writeln('🛠 *Equipment Maintenance Report Submitted*')
      ..writeln()
      ..writeln('*Conducted By:* ${conductedByUserName ?? "N/A"}')
      ..writeln('*Date:* ${maintenanceDate ?? "N/A"}')
      ..writeln('*Time:* ${timeStart ?? "-"} to ${timeEnd ?? "-"}')
      ..writeln('*Location:* ${location ?? "N/A"}')
      ..writeln('*Type:* ${isReplacement ? "Replacement" : "Routine Check"}')
      ..writeln('*Schedule:* ${scheduleMaintenance ?? "N/A"}');

    if (ysiSondeComments != null && ysiSondeComments!.isNotEmpty) {
      buffer.writeln('\n*YSI Remarks:* $ysiSondeComments');
    }

    if (vanDornComments != null && vanDornComments!.isNotEmpty) {
      buffer.writeln('\n*Van Dorn Remarks:* $vanDornComments');
    }

    buffer
      ..writeln()
      ..writeln('*Status of Submission:* Successful');

    return buffer.toString();
  }
// --- END: ADDED TELEGRAM METHOD ---
}