// lib/services/marine_manual_equipment_maintenance_service.dart

import 'dart:async';
import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:path/path.dart' as p;

import '../auth_provider.dart';
import '../models/marine_manual_equipment_maintenance_data.dart';
import 'api_service.dart';
import 'package:environment_monitoring_app/services/database_helper.dart';
import 'package:environment_monitoring_app/services/local_storage_service.dart';
import 'package:environment_monitoring_app/services/server_config_service.dart';
import 'package:environment_monitoring_app/services/retry_service.dart';
import 'package:environment_monitoring_app/services/submission_api_service.dart';
import 'package:environment_monitoring_app/services/submission_ftp_service.dart';
import 'package:environment_monitoring_app/services/zipping_service.dart';
import 'user_preferences_service.dart'; // ADDED
import 'telegram_service.dart'; // --- ADDED IMPORT ---

import 'base_api_service.dart'; // Import for SessionExpiredException

class MarineManualEquipmentMaintenanceService {
  // Use the new generic submission service
  final SubmissionApiService _submissionApiService = SubmissionApiService();
  final SubmissionFtpService _submissionFtpService = SubmissionFtpService();
  final ZippingService _zippingService = ZippingService();
  final LocalStorageService _localStorageService = LocalStorageService();
  final ServerConfigService _serverConfigService = ServerConfigService();
  final UserPreferencesService _userPreferencesService = UserPreferencesService(); // ADDED
  final DatabaseHelper _dbHelper = DatabaseHelper();
  final RetryService _retryService = RetryService();
  final TelegramService _telegramService; // --- ADDED FIELD ---

  // Keep ApiService for getPreviousMaintenanceLogs
  final ApiService _apiService;

  // --- MODIFIED CONSTRUCTOR ---
  MarineManualEquipmentMaintenanceService(this._apiService, this._telegramService);

  /// Fetches all Maintenance logs stored locally on the device.
  Future<List<Map<String, dynamic>>> getLocalMaintenanceLogs() async {
    return await _localStorageService.getAllEquipmentMaintenanceLogs();
  }

  /// Main submission method with online/offline branching logic
  Future<Map<String, dynamic>> submitMaintenanceReport({
    required MarineManualEquipmentMaintenanceData data,
    required AuthProvider authProvider,
    List<Map<String, dynamic>>? appSettings,
    BuildContext? context,
    String? logDirectory,
  }) async {
    // Unified module name for preferences
    const String moduleName = 'marine_report';

    // Populate the user name from the AuthProvider
    data.conductedByUserName = authProvider.profileData?['first_name'] as String?;

    final connectivityResult = await Connectivity().checkConnectivity();
    bool isOnline = !connectivityResult.contains(ConnectivityResult.none);
    bool isOfflineSession = authProvider.isLoggedIn &&
        (authProvider.profileData?['token']
            ?.startsWith("offline-session-") ??
            false);

    if (isOnline && isOfflineSession) {
      debugPrint(
          "$moduleName submission online during offline session. Attempting auto-relogin...");
      final bool transitionSuccess =
      await authProvider.checkAndTransitionToOnlineSession();
      if (transitionSuccess) {
        isOfflineSession = false;
      } else {
        isOnline = false;
      }
    }

    if (isOnline && !isOfflineSession) {
      debugPrint("Proceeding with direct ONLINE $moduleName submission...");
      return await _performOnlineSubmission(
        data: data,
        moduleName: moduleName,
        authProvider: authProvider,
        logDirectory: logDirectory,
      );
    } else {
      debugPrint("Proceeding with OFFLINE $moduleName queuing mechanism...");
      return await _performOfflineQueuing(
        data: data,
        moduleName: moduleName,
      );
    }
  }

  /// Handles the direct online submission.
  Future<Map<String, dynamic>> _performOnlineSubmission({
    required MarineManualEquipmentMaintenanceData data,
    required String moduleName,
    required AuthProvider authProvider,
    String? logDirectory,
  }) async {
    final serverName =
        (await _serverConfigService.getActiveApiConfig())?['config_name']
        as String? ??
            'Default';
    bool anyApiSuccess = false;
    Map<String, dynamic> apiResult = {};

    // 1. API Submission
    final pref = await _userPreferencesService.getModulePreference(moduleName);
    bool isApiEnabled = pref?['is_api_enabled'] ?? true;

    if (isApiEnabled) {
      try {
        apiResult = await _submissionApiService.submitPost(
          moduleName: moduleName,
          endpoint: 'marine/maintenance', // Endpoint from marine_api_service.dart
          body: data.toApiFormData(),
        );

        if (apiResult['success'] == false && (apiResult['message'] as String?)?.contains('Unauthorized') == true) {
          // Handle silent relogin
          if (await authProvider.attemptSilentRelogin()) {
            apiResult = await _submissionApiService.submitPost(
              moduleName: moduleName,
              endpoint: 'marine/maintenance',
              body: data.toApiFormData(),
            );
          }
        }

        if (apiResult['success'] == true) {
          anyApiSuccess = true;
          data.reportId = apiResult['data']?['maintenance_id']?.toString();
        }
      } on SocketException catch (e) {
        apiResult = {
          'success': false,
          'message': "API submission failed with network error: $e"
        };
        // Queue API manually if failed
        await _retryService.addApiToQueue(endpoint: 'marine/maintenance', method: 'POST', body: data.toApiFormData());
      } on TimeoutException catch (e) {
        apiResult = {
          'success': false,
          'message': "API submission timed out: $e"
        };
        await _retryService.addApiToQueue(endpoint: 'marine/maintenance', method: 'POST', body: data.toApiFormData());
      } catch (e) {
        apiResult = {
          'success': false,
          'message': 'An unexpected error occurred: $e'
        };
      }
    } else {
      anyApiSuccess = true; // Treat as success if disabled by user
    }

    // 2. FTP Submission (Data Zip Only - No Images for Maintenance)
    Map<String, dynamic> ftpResults = {'statuses': []};
    bool anyFtpSuccess = false;

    bool isFtpEnabled = pref?['is_ftp_enabled'] ?? true;
    // Check status to avoid duplicate uploads (L4 = API Fail, FTP Success; S4 = Both Success)
    bool previousFtpSuccess = data.submissionStatus == 'L4' || data.submissionStatus == 'S4';
    // Check active FTPs
    final enabledFtpConfigs = await _userPreferencesService.getEnabledFtpConfigsForModule(moduleName);

    if (!isFtpEnabled) {
      ftpResults = {'statuses': [{'status': 'Skipped', 'message': 'FTP disabled by user.', 'success': true}]};
      anyFtpSuccess = true;
    } else if (previousFtpSuccess) {
      debugPrint("FTP submission skipped: Already successful.");
      ftpResults = {'statuses': [{'status': 'Skipped', 'message': 'Already successful.', 'success': true}]};
      anyFtpSuccess = true;
    } else if (enabledFtpConfigs.isEmpty) {
      debugPrint("FTP submission skipped: No active FTP configurations found for $moduleName.");
      ftpResults = {'statuses': [{'status': 'Skipped', 'message': 'No active FTP servers.', 'success': true}]};
      anyFtpSuccess = true;
    } else {
      try {
        ftpResults = await _generateAndUploadFtpFiles(data, serverName, moduleName);
        anyFtpSuccess = !(ftpResults['statuses'] as List).any((status) => status['success'] == false && status['status'] != 'Not Configured');
      } catch (e) {
        debugPrint("FTP submission error: $e");
        anyFtpSuccess = false;
      }
    }

    // 3. Determine Final Status
    final bool overallSuccess = anyApiSuccess || anyFtpSuccess;
    String finalMessage;
    String finalStatus;

    if (anyApiSuccess && anyFtpSuccess) {
      finalMessage = 'Maintenance Report submitted successfully to all destinations.';
      finalStatus = 'S4';
    } else if (anyApiSuccess && !anyFtpSuccess) {
      finalMessage = 'Maintenance Report sent to API, but FTP upload failed.';
      finalStatus = 'S3';
    } else if (!anyApiSuccess && anyFtpSuccess) {
      finalMessage = 'API submission failed, but file sent to FTP.';
      finalStatus = 'L4';
    } else {
      finalMessage = apiResult['message'] ?? 'All submission attempts failed.';
      finalStatus = 'L1';
    }

    await _logAndSave(
      data: data,
      status: finalStatus,
      message: finalMessage,
      apiResult: apiResult,
      ftpStatuses: ftpResults['statuses'],
      serverName: serverName,
      logDirectory: logDirectory,
    );

    // --- START: ADDED TELEGRAM ALERT ---
    if (overallSuccess) {
      _handleSuccessAlert(data, authProvider);
    }
    // --- END: ADDED TELEGRAM ALERT ---

    return {'success': overallSuccess, 'message': finalMessage};
  }

  /// Handles saving the submission to local storage and queuing for retry.
  Future<Map<String, dynamic>> _performOfflineQueuing({
    required MarineManualEquipmentMaintenanceData data,
    required String moduleName,
  }) async {
    final serverConfig = await _serverConfigService.getActiveApiConfig();
    final serverName =
        serverConfig?['config_name'] as String? ?? 'Default';

    data.submissionStatus = 'L1';
    data.submissionMessage = 'Equipment Maintenance queued due to being offline.';

    // This method is added to LocalStorageService
    final String? localLogPath =
    await _localStorageService.saveEquipmentMaintenanceData(data, serverName: serverName);

    if (localLogPath == null) {
      const message =
          "Failed to save Equipment Maintenance to local device storage.";
      await _logAndSave(
          data: data,
          status: 'Error',
          message: message,
          apiResult: {},
          ftpStatuses: [],
          serverName: serverName);
      return {'success': false, 'message': message};
    }

    await _retryService.queueTask(
      type: 'equipment_maintenance_submission',
      payload: {
        'module': moduleName,
        'localLogPath': localLogPath,
        'serverConfig': serverConfig,
      },
    );

    const successMessage =
        "No internet connection. Equipment Maintenance has been saved and queued for upload.";
    return {'success': true, 'message': successMessage};
  }

  /// Generates zip files and uploads them via FTP.
  Future<Map<String, dynamic>> _generateAndUploadFtpFiles(MarineManualEquipmentMaintenanceData data, String serverName, String moduleName) async {
    final timestamp = data.maintenanceDate ?? DateTime.now().toIso8601String();
    final baseFileName = 'maintenance_$timestamp';

    final Directory? logDirectory = await _localStorageService.getLogDirectory(serverName: serverName, module: 'marine', subModule: 'marine_equipment_maintenance',);
    final Directory? localSubmissionDir = logDirectory != null ? Directory(p.join(logDirectory.path, baseFileName)) : null;
    if (localSubmissionDir != null && !await localSubmissionDir.exists()) await localSubmissionDir.create(recursive: true);

    final dataZip = await _zippingService.createDataZip(
      jsonDataMap: {'db.json': jsonEncode(data.toDbJson())},
      baseFileName: baseFileName,
      destinationDir: localSubmissionDir,
    );

    Map<String, dynamic> ftpDataResult = {'success': true, 'statuses': []};
    if (dataZip != null) {
      ftpDataResult = await _submissionFtpService.submit(
          moduleName: moduleName,
          fileToUpload: dataZip, // Added ! to ensure non-nullable
          remotePath: '/${p.basename(dataZip.path)}'
      );
    }

    return {'statuses': ftpDataResult['statuses'] ?? []};
  }

  /// Logs the submission to the local file system and the central SQL database.
  Future<void> _logAndSave({
    required MarineManualEquipmentMaintenanceData data,
    required String status,
    required String message,
    required Map<String, dynamic> apiResult,
    required List<Map<String, dynamic>> ftpStatuses,
    required String serverName,
    String? logDirectory,
  }) async {
    data.submissionStatus = status;
    data.submissionMessage = message;

    final fileTimestamp = data.maintenanceDate ?? DateTime.now().toIso8601String();

    // Use the new toDbJson() method to get ALL data for logging
    final Map<String, dynamic> logDataMap = data.toDbJson();
    // Add submission-specific metadata
    logDataMap['api_status'] = jsonEncode(apiResult);
    logDataMap['ftp_status'] = jsonEncode(ftpStatuses);
    logDataMap['serverConfigName'] = serverName;


    if (logDirectory != null) {
      // This is an update to an existing log file
      logDataMap['logDirectory'] = logDirectory;
      await _localStorageService.updateEquipmentMaintenanceLog(logDataMap);
    } else {
      // This is a new log
      await _localStorageService.saveEquipmentMaintenanceData(data, serverName: serverName);
    }

    final logData = {
      'submission_id': data.reportId ?? fileTimestamp,
      'module': 'marine',
      'type': 'Equipment Maintenance',
      'status': data.submissionStatus,
      'message': data.submissionMessage,
      'report_id': data.reportId,
      'created_at': DateTime.now().toIso8601String(),
      'form_data': jsonEncode(data.toDbJson()), // Log the full DbJson
      'image_data': null, // No images
      'server_name': serverName,
      'api_status': jsonEncode(apiResult),
      'ftp_status': jsonEncode(ftpStatuses),
    };
    await _dbHelper.saveSubmissionLog(logData);
  }

  /// Fetches previous maintenance logs to populate the form
  Future<Map<String, dynamic>> getPreviousMaintenanceLogs({
    required AuthProvider authProvider,
  }) async {
    try {
      return await _apiService.marine.getPreviousMaintenanceLogs();
    } on SessionExpiredException {
      final bool reloginSuccess = await authProvider.attemptSilentRelogin();
      if (reloginSuccess) {
        return await _apiService.marine.getPreviousMaintenanceLogs();
      } else {
        return {'success': false, 'message': 'Session expired. Please log in again.'};
      }
    } on SocketException {
      return {'success': false, 'message': 'Network error. Could not fetch previous records.'};
    } on TimeoutException {
      return {'success': false, 'message': 'Request timed out. Could not fetch previous records.'};
    } catch (e) {
      return {'success': false, 'message': 'An unexpected error occurred: $e'};
    }
  }

  // --- START: NEW TELEGRAM ALERT METHOD ---
  Future<void> _handleSuccessAlert(MarineManualEquipmentMaintenanceData data, AuthProvider authProvider) async {
    try {
      final message = data.generateTelegramAlertMessage();
      // Using 'marine_npe_report' ID/module config as requested
      if (!await _telegramService.sendAlertImmediately('marine_npe_report', message, authProvider.appSettings)) {
        await _telegramService.queueMessage('marine_npe_report', message, authProvider.appSettings);
      }
    } catch (e) {
      debugPrint("Telegram Alert Error (Maintenance): $e");
    }
  }
// --- END: NEW TELEGRAM ALERT METHOD ---
}