// lib/services/river_api_service.dart

import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';

import 'package:environment_monitoring_app/services/base_api_service.dart';
import 'package:environment_monitoring_app/services/telegram_service.dart';
import 'package:environment_monitoring_app/services/settings_service.dart';

class RiverApiService {
  final BaseApiService _baseService = BaseApiService();
  final TelegramService _telegramService = TelegramService();
  final SettingsService _settingsService = SettingsService();

  Future<Map<String, dynamic>> getManualStations() {
    return _baseService.get('river/manual-stations');
  }

  Future<Map<String, dynamic>> getTriennialStations() {
    return _baseService.get('river/triennial-stations');
  }

  Future<Map<String, dynamic>> submitInSituSample({
    required Map<String, String> formData,
    required Map<String, File?> imageFiles,
  }) async {
    // --- Step 1: Submit Form Data as JSON ---
    // The PHP backend for submitInSituSample expects JSON input.
    final dataResult = await _baseService.post('river/manual/sample', formData);

    if (dataResult['success'] != true) {
      return {
        'status': 'L1',
        'success': false,
        'message': 'Failed to submit river in-situ data: ${dataResult['message']}',
        'reportId': null
      };
    }

    // --- Step 2: Upload Image Files ---
    final recordId = dataResult['data']?['r_man_id'];
    if (recordId == null) {
      return {
        'status': 'L2',
        'success': false,
        'message': 'Data submitted, but failed to get a record ID for images.',
        'reportId': null
      };
    }

    final filesToUpload = <String, File>{};
    imageFiles.forEach((key, value) {
      if (value != null) filesToUpload[key] = value;
    });

    if (filesToUpload.isEmpty) {
      _handleInSituSuccessAlert(formData, isDataOnly: true);
      return {
        'status': 'L3',
        'success': true,
        'message': 'Data submitted successfully. No images were attached.',
        'reportId': recordId.toString()
      };
    }

    final imageResult = await _baseService.postMultipart(
      endpoint: 'river/manual/images', // Separate endpoint for images
      fields: {'r_man_id': recordId.toString()}, // Link images to the submitted record ID
      files: filesToUpload,
    );

    if (imageResult['success'] != true) {
      return {
        'status': 'L2',
        'success': false,
        'message': 'Data submitted, but image upload failed: ${imageResult['message']}',
        'reportId': recordId.toString()
      };
    }

    _handleInSituSuccessAlert(formData, isDataOnly: false);
    return {
      'status': 'L3',
      'success': true,
      'message': 'Data and images submitted successfully.',
      'reportId': recordId.toString()
    };
  }

  Future<void> _handleInSituSuccessAlert(Map<String, String> formData, {required bool isDataOnly}) async {
    try {
      final groupChatId = await _settingsService.getInSituChatId();
      if (groupChatId.isNotEmpty) {
        final submissionType = isDataOnly ? "(Data Only)" : "(Data & Images)";
        final stationName = formData['r_man_station_name'] ?? 'N/A';
        final stationCode = formData['r_man_station_code'] ?? 'N/A';
        final submissionDate = formData['r_man_date'] ?? DateFormat('yyyy-MM-dd').format(DateTime.now());
        final submitter = formData['first_sampler_name'] ?? 'N/A';
        final sondeID = formData['r_man_sondeID'] ?? 'N/A';
        final distanceKm = double.tryParse(formData['r_man_distance_difference'] ?? '0') ?? 0;
        final distanceMeters = (distanceKm * 1000).toStringAsFixed(0);
        final distanceRemarks = formData['r_man_distance_difference_remarks'] ?? '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('🔔 *Alert:*')
            ..writeln('*Distance from station:* $distanceMeters meters');
          if (distanceRemarks.isNotEmpty && distanceRemarks != 'N/A') {
            buffer.writeln('*Remarks for distance:* $distanceRemarks');
          }
        }

        final String message = buffer.toString();

        final bool wasSent = await _telegramService.sendAlertImmediately('river_in_situ', message);
        if (!wasSent) {
          await _telegramService.queueMessage('river_in_situ', message);
        }
      }
    } catch (e) {
      debugPrint("Failed to handle River Telegram alert: $e");
    }
  }
}