import 'dart:convert';
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/server_config_service.dart';
import 'package:environment_monitoring_app/services/api_service.dart'; // For imageBaseUrl

// --- ADDED: Imports for data models ---
import 'package:environment_monitoring_app/models/marine_manual_pre_departure_checklist_data.dart';
import 'package:environment_monitoring_app/models/marine_manual_sonde_calibration_data.dart';
import 'package:environment_monitoring_app/models/marine_manual_equipment_maintenance_data.dart';

class MarineApiService {
  final BaseApiService _baseService;
  final TelegramService _telegramService;
  final ServerConfigService _serverConfigService;

  MarineApiService(this._baseService, this._telegramService, this._serverConfigService);

  // --- METHODS YOU ALREADY MOVED ---
  Future<Map<String, dynamic>> getTarballStations() async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();
    return _baseService.get(baseUrl, 'marine/tarball/stations');
  }

  Future<Map<String, dynamic>> getManualStations() async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();
    return _baseService.get(baseUrl, 'marine/manual/stations');
  }

  Future<Map<String, dynamic>> getTarballClassifications() async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();
    return _baseService.get(baseUrl, 'marine/tarball/classifications');
  }

  Future<Map<String, dynamic>> getManualSamplingImages({
    required int stationId,
    required DateTime samplingDate,
    required String samplingType, // This parameter is now used
  }) async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();
    final String dateStr = DateFormat('yyyy-MM-dd').format(samplingDate);

    String endpoint;
    switch (samplingType) {
      case 'In-Situ Sampling':
        endpoint = 'marine/manual/records-by-station?station_id=$stationId&date=$dateStr';
        break;
      case 'Tarball Sampling':
        endpoint = 'marine/tarball/records-by-station?station_id=$stationId&date=$dateStr';
        break;
      case 'All Manual Sampling':
      default:
        endpoint = 'marine/manual/records-by-station?station_id=$stationId&date=$dateStr';
        break;
    }

    debugPrint("MarineApiService: Calling API endpoint: $endpoint");
    final response = await _baseService.get(baseUrl, endpoint);

    if (response['success'] == true && response['data'] is Map && response['data']['data'] is List) {
      return {
        'success': true,
        'data': response['data']['data'], // Return the inner 'data' list
        'message': response['message'],
      };
    }
    return response;
  }

  Future<Map<String, dynamic>> sendImageRequestEmail({
    required String recipientEmail,
    required List<String> imageUrls,
    required String stationName,
    required String samplingDate,
  }) async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();

    final Map<String, String> fields = {
      'recipientEmail': recipientEmail,
      'imageUrls': jsonEncode(imageUrls),
      'stationName': stationName,
      'samplingDate': samplingDate,
    };

    return _baseService.postMultipart(
      baseUrl: baseUrl,
      endpoint: 'marine/images/send-email',
      fields: fields,
      files: {},
    );
  }

  // --- START: ADDED MISSING METHODS ---
  Future<Map<String, dynamic>> submitPreDepartureChecklist(MarineManualPreDepartureChecklistData data) async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();
    return _baseService.post(baseUrl, 'marine/checklist', data.toApiFormData());
  }

  Future<Map<String, dynamic>> submitSondeCalibration(MarineManualSondeCalibrationData data) async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();
    return _baseService.post(baseUrl, 'marine/calibration', data.toApiFormData());
  }

  Future<Map<String, dynamic>> submitMaintenanceLog(MarineManualEquipmentMaintenanceData data) async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();
    return _baseService.post(baseUrl, 'marine/maintenance', data.toApiFormData());
  }

  Future<Map<String, dynamic>> getPreviousMaintenanceLogs() async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();
    return _baseService.get(baseUrl, 'marine/maintenance/previous');
  }
  // --- END: ADDED MISSING METHODS ---

  // *** START: ADDED FOR NPE REPORTS ***
  /// Fetches all NPE Reports submitted by the user (requires auth).
  Future<Map<String, dynamic>> getAllNpeReports() async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();
    // Corresponds to the new GET /marine/npe route in index.php
    final response = await _baseService.get(baseUrl, 'marine/npe');

    // Assuming the response returns the array of reports directly under the 'data' key
    if (response['success'] == true && response['data'] is List) {
      return response;
    }
    // Handle error or empty response
    if (response['success'] == true && response['data'] == null) {
      return {'success': true, 'data': [], 'message': 'No reports found.'};
    }
    return response;
  }
  // *** END: ADDED FOR NPE REPORTS ***

  // *** START: ADDED FOR INVESTIGATIVE IMAGE REQUEST ***

  /// Fetches investigative sampling records based on station and date.
  /// This will check against investigative logs which could have used either a manual or tarball station.
  Future<Map<String, dynamic>> getInvestigativeSamplingImages({
    required int stationId,
    required DateTime samplingDate,
    required String stationType, // 'Existing Manual Station' or 'Existing Tarball Station'
  }) async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();
    final String dateStr = DateFormat('yyyy-MM-dd').format(samplingDate);

    // Pass the station type to the API so it knows which foreign key to check (station_id vs tbl_station_id)
    final String stationTypeParam = Uri.encodeComponent(stationType);

    // *** FIX: Use the correct top-level resource name 'marine-investigative' ***
    final String endpoint =
        'marine-investigative/records-by-station?station_id=$stationId&date=$dateStr&station_type=$stationTypeParam';

    debugPrint("MarineApiService: Calling API endpoint: $endpoint");
    final response = await _baseService.get(baseUrl, endpoint);

    // Assuming the response structure is the same as the manual/tarball endpoints
    if (response['success'] == true && response['data'] is Map && response['data']['data'] is List) {
      return {
        'success': true,
        'data': response['data']['data'], // Return the inner 'data' list
        'message': response['message'],
      };
    }
    return response;
  }

  /// Sends an email request for investigative images.
  Future<Map<String, dynamic>> sendInvestigativeImageRequestEmail({
    required String recipientEmail,
    required List<String> imageUrls,
    required String stationName,
    required String samplingDate,
  }) async {
    final baseUrl = await _serverConfigService.getActiveApiUrl();

    final Map<String, String> fields = {
      'recipientEmail': recipientEmail,
      'imageUrls': jsonEncode(imageUrls),
      'stationName': stationName,
      'samplingDate': samplingDate,
    };

    // *** FIX: Use the correct top-level resource name 'marine-investigative' ***
    return _baseService.postMultipart(
      baseUrl: baseUrl,
      endpoint: 'marine-investigative/images/send-email',
      fields: fields,
      files: {},
    );
  }
// *** END: ADDED FOR INVESTIGATIVE IMAGE REQUEST ***
}