// lib/services/river_in_situ_sampling_service.dart

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
import 'package:image/image.dart' as img;
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:usb_serial/usb_serial.dart';
import 'dart:convert';
import 'package:intl/intl.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:provider/provider.dart';

import '../auth_provider.dart';
import 'location_service.dart';
import '../models/river_in_situ_sampling_data.dart';
import '../bluetooth/bluetooth_manager.dart';
import '../serial/serial_manager.dart';
import 'api_service.dart';
import 'local_storage_service.dart';
import 'server_config_service.dart';
import 'zipping_service.dart';
import 'submission_api_service.dart';
import 'submission_ftp_service.dart';
import 'telegram_service.dart';
import 'retry_service.dart';
import 'base_api_service.dart'; // Import for SessionExpiredException


class RiverInSituSamplingService {
  final LocationService _locationService = LocationService();
  final BluetoothManager _bluetoothManager = BluetoothManager();
  final SerialManager _serialManager = SerialManager();
  final SubmissionApiService _submissionApiService = SubmissionApiService();
  final SubmissionFtpService _submissionFtpService = SubmissionFtpService();
  final DatabaseHelper _dbHelper = DatabaseHelper();
  final LocalStorageService _localStorageService = LocalStorageService();
  final ServerConfigService _serverConfigService = ServerConfigService();
  final ZippingService _zippingService = ZippingService();
  final RetryService _retryService = RetryService();
  final TelegramService _telegramService;
  final ImagePicker _picker = ImagePicker();

  static const platform = MethodChannel('com.example.environment_monitoring_app/usb');

  RiverInSituSamplingService(this._telegramService);

  Future<Position> getCurrentLocation() => _locationService.getCurrentLocation();
  double calculateDistance(double lat1, double lon1, double lat2, double lon2) => _locationService.calculateDistance(lat1, lon1, lat2, lon2);

  Future<File?> pickAndProcessImage(ImageSource source, { required RiverInSituSamplingData data, required String imageInfo, bool isRequired = false, String? stationCode}) async {
    try {
      final XFile? pickedFile = await _picker.pickImage(
        source: source,
        imageQuality: 85,
        maxWidth: 1024,
      );

      if (pickedFile == null) {
        return null;
      }

      final bytes = await pickedFile.readAsBytes();
      img.Image? originalImage = img.decodeImage(bytes);
      if (originalImage == null) {
        return null;
      }

      if (isRequired && originalImage.height > originalImage.width) {
        debugPrint("Image rejected: Must be in landscape orientation.");
        return null;
      }

      final String watermarkTimestamp = "${data.samplingDate} ${data.samplingTime}";
      final font = img.arial24;
      final textWidth = watermarkTimestamp.length * 12;
      img.fillRect(originalImage, x1: 5, y1: 5, x2: textWidth + 15, y2: 35, color: img.ColorRgb8(255, 255, 255),);
      img.drawString(originalImage, watermarkTimestamp, font: font, x: 10, y: 10, color: img.ColorRgb8(0, 0, 0));

      final tempDir = await getTemporaryDirectory();
      final finalStationCode = stationCode ?? 'NA';
      final fileTimestamp = "${data.samplingDate}-${data.samplingTime}".replaceAll(':', '-');
      final newFileName = "${finalStationCode}_${fileTimestamp}_${imageInfo.replaceAll(' ', '')}.jpg";
      final filePath = p.join(tempDir.path, newFileName);

      return File(filePath)..writeAsBytesSync(img.encodeJpg(originalImage));

    } catch (e) {
      debugPrint('Error in pickAndProcessImage: $e');
      return null;
    }
  }

  ValueNotifier<BluetoothConnectionState> get bluetoothConnectionState => _bluetoothManager.connectionState;
  ValueNotifier<SerialConnectionState> get serialConnectionState => _serialManager.connectionState;

  ValueNotifier<String?> get sondeId {
    if (_bluetoothManager.connectionState.value != BluetoothConnectionState.disconnected) {
      return _bluetoothManager.sondeId;
    }
    return _serialManager.sondeId;
  }

  Stream<Map<String, double>> get bluetoothDataStream => _bluetoothManager.dataStream;
  Stream<Map<String, double>> get serialDataStream => _serialManager.dataStream;
  String? get connectedBluetoothDeviceName => _bluetoothManager.connectedDeviceName.value;
  String? get connectedSerialDeviceName => _serialManager.connectedDeviceName.value;

  Future<bool> requestDevicePermissions() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.bluetoothScan,
      Permission.bluetoothConnect,
      Permission.locationWhenInUse,
    ].request();

    if (statuses[Permission.bluetoothScan] == PermissionStatus.granted &&
        statuses[Permission.bluetoothConnect] == PermissionStatus.granted) {
      return true;
    } else {
      return false;
    }
  }

  Future<List<BluetoothDevice>> getPairedBluetoothDevices() => _bluetoothManager.getPairedDevices();
  Future<void> connectToBluetoothDevice(BluetoothDevice device) => _bluetoothManager.connect(device);
  void disconnectFromBluetooth() => _bluetoothManager.disconnect();
  void startBluetoothAutoReading({Duration? interval}) => _bluetoothManager.startAutoReading(interval: interval ?? const Duration(seconds: 2));
  void stopBluetoothAutoReading() => _bluetoothManager.stopAutoReading();
  Future<List<UsbDevice>> getAvailableSerialDevices() => _serialManager.getAvailableDevices();

  Future<bool> requestUsbPermission(UsbDevice device) async {
    try {
      return await platform.invokeMethod('requestUsbPermission', {'vid': device.vid, 'pid': device.pid}) ?? false;
    } on PlatformException catch (e) {
      debugPrint("Failed to request USB permission: '${e.message}'.");
      return false;
    }
  }

  Future<void> connectToSerialDevice(UsbDevice device) async {
    final bool permissionGranted = await requestUsbPermission(device);
    if (permissionGranted) {
      await _serialManager.connect(device);
    } else {
      throw Exception("USB permission was not granted.");
    }
  }

  void disconnectFromSerial() => _serialManager.disconnect();
  void startSerialAutoReading({Duration? interval}) => _serialManager.startAutoReading(interval: interval ?? const Duration(seconds: 2));
  void stopSerialAutoReading() => _serialManager.stopAutoReading();
  void dispose() {
    _bluetoothManager.dispose();
    _serialManager.dispose();
  }

  Future<Map<String, dynamic>> submitData({
    required RiverInSituSamplingData data,
    required List<Map<String, dynamic>>? appSettings,
    required AuthProvider authProvider,
    String? logDirectory,
  }) async {
    const String moduleName = 'river_in_situ';

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

    if (isOnline && isOfflineSession) {
      debugPrint("River In-Situ 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 River In-Situ submission...");
      return await _performOnlineSubmission(
        data: data,
        appSettings: appSettings,
        moduleName: moduleName,
        authProvider: authProvider,
        logDirectory: logDirectory,
      );
    } else {
      debugPrint("Proceeding with OFFLINE River In-Situ queuing mechanism...");
      return await _performOfflineQueuing(
        data: data,
        moduleName: moduleName,
      );
    }
  }

  Future<Map<String, dynamic>> _performOnlineSubmission({
    required RiverInSituSamplingData data,
    required List<Map<String, dynamic>>? appSettings,
    required String moduleName,
    required AuthProvider authProvider,
    String? logDirectory,
  }) async {
    final serverName = (await _serverConfigService.getActiveApiConfig())?['config_name'] as String? ?? 'Default';
    final imageFilesWithNulls = data.toApiImageFiles();
    imageFilesWithNulls.removeWhere((key, value) => value == null);
    final Map<String, File> finalImageFiles = imageFilesWithNulls.cast<String, File>();

    bool anyApiSuccess = false;
    Map<String, dynamic> apiDataResult = {};
    Map<String, dynamic> apiImageResult = {};
    bool isSessionKnownToBeExpired = false;

    try {
      apiDataResult = await _submissionApiService.submitPost(
        moduleName: moduleName,
        endpoint: 'river/manual/sample',
        body: data.toApiFormData(),
      );

      if (apiDataResult['success'] == true) {
        anyApiSuccess = true;
        data.reportId = apiDataResult['data']?['r_man_id']?.toString();

        if (data.reportId != null) {
          if (finalImageFiles.isNotEmpty) {
            apiImageResult = await _submissionApiService.submitMultipart(
              moduleName: moduleName,
              endpoint: 'river/manual/images',
              fields: {'r_man_id': data.reportId!},
              files: finalImageFiles,
            );
            if (apiImageResult['success'] != true) {
              anyApiSuccess = false;
            }
          }
        } else {
          anyApiSuccess = false;
          apiDataResult['message'] = 'API Error: Submission succeeded but did not return a record ID.';
        }
      }
    } on SessionExpiredException catch (_) {
      debugPrint("API submission failed with SessionExpiredException. Attempting silent relogin...");
      final bool reloginSuccess = await authProvider.attemptSilentRelogin();

      if (reloginSuccess) {
        debugPrint("Silent relogin successful. Retrying entire online submission process...");
        return await _performOnlineSubmission(
          data: data,
          appSettings: appSettings,
          moduleName: moduleName,
          authProvider: authProvider,
          logDirectory: logDirectory,
        );
      } else {
        debugPrint("Silent relogin failed. API part will be queued, proceeding with FTP.");
        isSessionKnownToBeExpired = true;
        anyApiSuccess = false;
        apiDataResult = {'success': false, 'message': 'Session expired and re-login failed. API submission queued.'};
        await _retryService.addApiToQueue(endpoint: 'river/manual/sample', method: 'POST', body: data.toApiFormData());
      }
    } on SocketException catch (e) {
      final errorMessage = "API submission failed with network error: $e";
      debugPrint(errorMessage);
      anyApiSuccess = false;
      apiDataResult = {'success': false, 'message': errorMessage};
      await _retryService.addApiToQueue(endpoint: 'river/manual/sample', method: 'POST', body: data.toApiFormData());
      if (finalImageFiles.isNotEmpty && data.reportId != null) {
        await _retryService.addApiToQueue(endpoint: 'river/manual/images', method: 'POST_MULTIPART', fields: {'r_man_id': data.reportId!}, files: finalImageFiles);
      }
    } on TimeoutException catch (e) {
      final errorMessage = "API submission timed out: $e";
      debugPrint(errorMessage);
      anyApiSuccess = false;
      apiDataResult = {'success': false, 'message': errorMessage};
      await _retryService.addApiToQueue(endpoint: 'river/manual/sample', method: 'POST', body: data.toApiFormData());
    }

    Map<String, dynamic> ftpResults = {'statuses': []};
    bool anyFtpSuccess = false;
    try {
      ftpResults = await _generateAndUploadFtpFiles(data, finalImageFiles, serverName, moduleName);
      anyFtpSuccess = !(ftpResults['statuses'] as List).any((status) => status['success'] == false && status['status'] != 'Not Configured');
    } on SocketException catch (e) {
      debugPrint("FTP submission failed with network error: $e");
      anyFtpSuccess = false;
    } on TimeoutException catch (e) {
      debugPrint("FTP submission timed out: $e");
      anyFtpSuccess = false;
    }

    final bool overallSuccess = anyApiSuccess || anyFtpSuccess;
    String finalMessage;
    String finalStatus;

    if (anyApiSuccess && anyFtpSuccess) {
      finalMessage = 'Data submitted successfully to all destinations.';
      finalStatus = 'S4';
    } else if (anyApiSuccess && !anyFtpSuccess) {
      finalMessage = 'Data sent to API, but some FTP uploads failed and were queued.';
      finalStatus = 'S3';
    } else if (!anyApiSuccess && anyFtpSuccess) {
      finalMessage = 'API submission failed and was queued, but files were sent to FTP successfully.';
      finalStatus = 'L4';
    } else {
      finalMessage = apiDataResult['message'] ?? 'All submission attempts failed and have been queued for retry.';
      finalStatus = 'L1';
    }

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

    if (overallSuccess) {
      _handleSuccessAlert(data, appSettings, isDataOnly: finalImageFiles.isEmpty, isSessionExpired: isSessionKnownToBeExpired);
    }

    return {
      'status': finalStatus,
      'success': overallSuccess,
      'message': finalMessage,
      'reportId': data.reportId
    };
  }

  Future<Map<String, dynamic>> _performOfflineQueuing({
    required RiverInSituSamplingData data,
    required String moduleName,
  }) async {
    final serverConfig = await _serverConfigService.getActiveApiConfig();
    final serverName = serverConfig?['config_name'] as String? ?? 'Default';

    data.submissionStatus = 'L1';
    data.submissionMessage = 'Submission queued for later retry.';

    final String? localLogPath = await _localStorageService.saveRiverInSituSamplingData(data, serverName: serverName);

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

    await _retryService.queueTask(
      type: 'river_insitu_submission',
      payload: {
        'module': moduleName,
        'localLogPath': p.join(localLogPath, 'data.json'),
        'serverConfig': serverConfig,
      },
    );

    const successMessage = "Submission failed to send and has been queued for later retry.";
    return {'status': 'Queued', 'success': true, 'message': successMessage};
  }

  Future<Map<String, dynamic>> _generateAndUploadFtpFiles(RiverInSituSamplingData data, Map<String, File> imageFiles, String serverName, String moduleName) async {
    final stationCode = data.selectedStation?['sampling_station_code'] ?? 'UNKNOWN';
    final fileTimestamp = "${data.samplingDate}_${data.samplingTime}".replaceAll(':', '-').replaceAll(' ', '_');
    final baseFileName = "${stationCode}_$fileTimestamp";

    final Directory? logDirectory = await _localStorageService.getLogDirectory(
      serverName: serverName,
      module: 'river',
      subModule: 'river_in_situ_sampling',
    );

    final Directory? localSubmissionDir = logDirectory != null ? Directory(p.join(logDirectory.path, data.reportId ?? baseFileName)) : null;
    if (localSubmissionDir != null && !await localSubmissionDir.exists()) {
      await localSubmissionDir.create(recursive: true);
    }

    final dataZip = await _zippingService.createDataZip(
      jsonDataMap: {'db.json': jsonEncode(data.toApiFormData())},
      baseFileName: baseFileName,
      destinationDir: localSubmissionDir,
    );
    Map<String, dynamic> ftpDataResult = {'success': true, 'statuses': []};
    if (dataZip != null) {
      ftpDataResult = await _submissionFtpService.submit(
          moduleName: moduleName, fileToUpload: dataZip, remotePath: '/${p.basename(dataZip.path)}');
    }

    final imageZip = await _zippingService.createImageZip(
      imageFiles: imageFiles.values.toList(),
      baseFileName: baseFileName,
      destinationDir: localSubmissionDir,
    );
    Map<String, dynamic> ftpImageResult = {'success': true, 'statuses': []};
    if (imageZip != null) {
      ftpImageResult = await _submissionFtpService.submit(
          moduleName: moduleName, fileToUpload: imageZip, remotePath: '/${p.basename(imageZip.path)}');
    }

    return {
      'statuses': <Map<String, dynamic>>[
        ...(ftpDataResult['statuses'] as List),
        ...(ftpImageResult['statuses'] as List),
      ],
    };
  }

  Future<void> _logAndSave({
    required RiverInSituSamplingData data,
    required String status,
    required String message,
    required List<Map<String, dynamic>> apiResults,
    required List<Map<String, dynamic>> ftpStatuses,
    required String serverName,
    String? logDirectory,
  }) async {
    data.submissionStatus = status;
    data.submissionMessage = message;

    if (logDirectory != null) {
      final Map<String, dynamic> updatedLogData = data.toMap();
      updatedLogData['logDirectory'] = logDirectory;
      updatedLogData['serverConfigName'] = serverName;
      updatedLogData['api_status'] = jsonEncode(apiResults.where((r) => r.isNotEmpty).toList());
      updatedLogData['ftp_status'] = jsonEncode(ftpStatuses);

      final imageFilePaths = data.toApiImageFiles();
      imageFilePaths.forEach((key, file) {
        if (file != null) {
          updatedLogData[key] = file.path;
        }
      });

      await _localStorageService.updateRiverInSituLog(updatedLogData);
    } else {
      await _localStorageService.saveRiverInSituSamplingData(data, serverName: serverName);
    }

    final imagePaths = data.toApiImageFiles().values.whereType<File>().map((f) => f.path).toList();
    final logData = {
      'submission_id': data.reportId ?? DateTime.now().millisecondsSinceEpoch.toString(),
      'module': 'river', 'type': data.samplingType ?? 'In-Situ', 'status': status,
      'message': message, 'report_id': data.reportId, 'created_at': DateTime.now().toIso8601String(),
      'form_data': jsonEncode(data.toMap()), 'image_data': jsonEncode(imagePaths),
      'server_name': serverName, 'api_status': jsonEncode(apiResults), 'ftp_status': jsonEncode(ftpStatuses),
    };
    await _dbHelper.saveSubmissionLog(logData);
  }

  Future<void> _handleSuccessAlert(RiverInSituSamplingData data, List<Map<String, dynamic>>? appSettings, {required bool isDataOnly, bool isSessionExpired = false}) async {
    try {
      final message = await _generateInSituAlertMessage(data, isDataOnly: isDataOnly);
      if (isSessionExpired) {
        debugPrint("Session is expired; queuing Telegram alert directly.");
        await _telegramService.queueMessage('river_in_situ', message, appSettings);
      } else {
        final bool wasSent = await _telegramService.sendAlertImmediately('river_in_situ', message, appSettings);
        if (!wasSent) {
          await _telegramService.queueMessage('river_in_situ', message, appSettings);
        }
      }
    } catch (e) {
      debugPrint("Failed to handle River Telegram alert: $e");
    }
  }

  Future<String> _generateInSituAlertMessage(RiverInSituSamplingData data, {required bool isDataOnly}) async {
    final submissionType = isDataOnly ? "(Data Only)" : "(Data & Images)";
    final stationName = data.selectedStation?['sampling_river'] ?? 'N/A';
    final stationCode = data.selectedStation?['sampling_station_code'] ?? 'N/A';
    final submissionDate = data.samplingDate ?? DateFormat('yyyy-MM-dd').format(DateTime.now());
    final submitter = data.firstSamplerName ?? 'N/A';
    final sondeID = data.sondeId ?? 'N/A';
    final distanceKm = data.distanceDifferenceInKm ?? 0;
    final distanceMeters = (distanceKm * 1000).toStringAsFixed(0);
    final distanceRemarks = data.distanceDifferenceRemarks ?? 'N/A';

    final buffer = StringBuffer()
      ..writeln('✅ *River In-Situ Sample ${submissionType} Submitted:*')
      ..writeln()
      ..writeln('*Station Name & Code:* $stationName ($stationCode)')
      ..writeln('*Date of Submitted:* $submissionDate')
      ..writeln('*Submitted by User:* $submitter')
      ..writeln('*Sonde ID:* $sondeID')
      ..writeln('*Status of Submission:* Successful');

    if (distanceKm > 0 || (distanceRemarks.isNotEmpty && distanceRemarks != 'N/A')) {
      buffer
        ..writeln()
        ..writeln('🔔 *Distance Alert:*')
        ..writeln('*Distance from station:* $distanceMeters meters');
      if (distanceRemarks.isNotEmpty && distanceRemarks != 'N/A') {
        buffer.writeln('*Remarks for distance:* $distanceRemarks');
      }
    }
    return buffer.toString();
  }
}