import 'dart:async';
import 'dart:ffi';

import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/core/model/pharmacy-intervention-model/intervention_history.dart';
import 'package:doctor_app_flutter/core/model/pharmacy-intervention-model/nursing_station.dart';
import 'package:doctor_app_flutter/core/model/pharmacy-intervention-model/pharmacy_intervention_item.dart';
import 'package:doctor_app_flutter/core/service/base/base_service.dart';
import 'package:doctor_app_flutter/core/service/hospitals/hospitals_service.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.dart';
import 'package:intl/intl.dart';

class PharmacyInterventionService extends BaseService {
  Future<MedicationList?> getMedicationList(
      {String nursingStationId = '0',
      String admissionId = '0',
      String patientID = '0',
      String fromDate = '',
      String toDate = ''}) async {
    Map<String,dynamic> request = {
      "NursingStationID": nursingStationId.isEmpty?'0':nursingStationId,
      "AdmissionNo": admissionId.isEmpty ?'0': admissionId,
      "PatientID": num.parse((patientID.isEmpty)?'0':patientID),
    };
    if(fromDate.isNotEmpty){
      var temp  = {
        "InterventionFromDate": convertToISO8601(fromDate).toString(),
        "InterventionToDate":  convertToISO8601(toDate).toString(),
      };
      request.addAll(temp);
    }

    hasError = false;
    MedicationList? result;
     await baseAppClient.post(GET_MEDICINE_WITH_INTERVAL,
        onSuccess: (dynamic response, int statusCode) {
      result =  MedicationList.fromJson(response['List_MedicineWithIntervention']);
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      DrAppToastMsg.showErrorToast(error);
      super.error = super.error??'' + "\n" + error;

    }, body: request);

    return result;
  }

  String convertToISO8601(String dateString) {
    try {
      DateFormat inputFormat = DateFormat('yyyy-MM-dd'); // Adjust format if needed
      DateTime parsedDate = inputFormat.parse(dateString);
      String iso8601String = parsedDate.toIso8601String().toString();
      print('the data is $iso8601String');
      return iso8601String; // Remove milliseconds
    } catch (e) {
      return "Invalid date format: $e";
    }
  }

  ///
  ///  it will be called only for the doctor that are associated to vida plus
  ///  project
  ///
  Future<bool> getInfectiousDiseaseConsultantStatus() async {
    String vidaToken = await sharedPref.getString(VIDA_AUTH_TOKEN_ID);

    if(vidaToken.isEmpty){
      return false;
    }
    hasError = false;
    var success = false;
    await baseAppClient.post(IS_INFECTIOUS_DISEASE_CONSULTANT,
        onSuccess: (dynamic response, int statusCode) {
        success = response['IsInfectiousDiseases'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      DrAppToastMsg.showErrorToast(error);

    }, body: {});
  return success;
  }

  Future<bool> getPendingInterventionDiseaseStatus() async {
    String vidaToken = await sharedPref.getString(VIDA_AUTH_TOKEN_ID);
    if(vidaToken.isEmpty){
      return false;
    }
    hasError = false;
    var success = false;
    await baseAppClient.post(IS_INFECTIOUS_DISEASE_PENDING,
        onSuccess: (dynamic response, int statusCode) {
          success = response['IsPending'];
        }, onFailure: (String error, int statusCode) {
          hasError = true;
          DrAppToastMsg.showErrorToast(error);
        }, body: {});
    return success;
  }

  Future<InterventionHistoryList?> getInfectiousDiseaseHistory({
    int admissionNumber = 0,
    int prescriptionNumber = 0,
    int orderNumber = 0,
    int itemID = 0,
    dynamic memberID,
  }) async {
    var request = {
      "AdmissionNo": admissionNumber,
      "PrescriptionNo": prescriptionNumber,
      "OrderNo": orderNumber,
      "ItemID": itemID,
      "MemberID": memberID,
    };

    hasError = false;
    InterventionHistoryList? result;
     await baseAppClient.post(INFECTIOUS_HISTORY,
        onSuccess: (dynamic response, int statusCode) {
      result =  InterventionHistoryList.fromJson(
          response['List_MedicineInterventionHistory']);
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      DrAppToastMsg.showErrorToast(error);
    }, body: request);
    return result;
  }

  Future<bool> updateInterventionStatus(
    Map<String, dynamic> request
  ) async {
    hasError = false;
    var result = false;
     await baseAppClient.post(UPDATE_INFECTIOUS_STATUS,
        onSuccess: (dynamic response, int statusCode) {
      result = response['IsAccepted'] ?? false;
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      DrAppToastMsg.showErrorToast(error);
    }, body: request);
    return result;
  }


  Future<NursingStation?> getNursingStation() async{
    hasError = false;
    NursingStation? station;
    await baseAppClient.post(GET_NURSING_STATIONS,
        onSuccess: (dynamic response, int statusCode) {
          station = NursingStation.fromJson(response['AdmissionMasterList']);
        }, onFailure: (String error, int statusCode) {
          hasError = true;
          DrAppToastMsg.showErrorToast(error);
        }, body: {});
    return station;
  }
}
