import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/model/insurance/Insurance_card_details.dart';
import 'package:hmg_patient_app/core/model/insurance/ReauestInsuranceApprovalModel.dart';
import 'package:hmg_patient_app/core/model/insurance/insuranceManualUpdateRequest.dart';
import 'package:hmg_patient_app/core/model/insurance/insurance_approval.dart';
import 'package:hmg_patient_app/core/model/insurance/insurance_card.dart';
import 'package:hmg_patient_app/core/model/insurance/insurance_card_update_model.dart';
import 'package:hmg_patient_app/core/service/base_service.dart';
import 'package:hmg_patient_app/models/FamilyFiles/GetAllSharedRecordByStatusResponse.dart';
import 'package:hmg_patient_app/models/FamilyFiles/GetAllSharedRecordsByStatusReq.dart';
import 'package:hmg_patient_app/services/family_files/family_files_provider.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:flutter/material.dart';

class InsuranceCardService extends BaseService {
  List<InsuranceCardModel> _cardList =[];
  List<InsuranceUpdateModel> _cardUpdated =[];
  List<InsuranceApprovalModel> _insuranceApproval =[];

  List<InsuranceCardModel> get cardList => _cardList;

  List<InsuranceUpdateModel> get updatedCard => _cardUpdated;

  List<InsuranceApprovalModel> get insuranceApproval => _insuranceApproval;

  InsuranceCardDetailsModel? insuranceCardDetails;
  List<InsuranceCardDetailsModel> insuranceCardDetailsList =[];
  bool isHaveInsuranceCard = false;

  GetAllSharedRecordsByStatusResponse getAllSharedRecordsByStatusResponse = GetAllSharedRecordsByStatusResponse();

  clearInsuranceCard() {
    _cardList.clear();
  }

  clearUpdatedList() {
    _cardUpdated.clear();
  }

  RequestInsuranceApprovalModel _requestInsuranceApprovalModel = RequestInsuranceApprovalModel(isDentalAllowedBackend: false, patientTypeID: 1, patientType: 1, eXuldAPPNO: 0, projectID: 0);

  Future getInsurance() async {
    hasError = false;
    _cardList.clear();
    await baseAppClient.post(GET_PAtIENTS_INSURANCE, onSuccess: (dynamic response, int statusCode) {
      response['List_PatientInsuranceCard'].forEach((item) {
        _cardList.add(InsuranceCardModel.fromJson(item));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: Map());
  }

  Future getInsuranceUpdate() async {
    hasError = false;
    _cardList.clear();
    await baseAppClient.post(GET_PAtIENTS_INSURANCE_UPDATED, onSuccess: (dynamic response, int statusCode) {
      _cardUpdated.clear();
      response['List_PatientInsuranceCardHistory'].forEach((item) {
        _cardUpdated.add(InsuranceUpdateModel.fromJson(item));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: Map());
  }

  Future getInsuranceApproval({int? appointmentNo}) async {
    hasError = false;
    if (appointmentNo != null) {
      _requestInsuranceApprovalModel.appointmentNo = appointmentNo;
      _requestInsuranceApprovalModel.eXuldAPPNO = 0;
      _requestInsuranceApprovalModel.projectID = 0;
    } else {
      _requestInsuranceApprovalModel.appointmentNo = 0;
      _requestInsuranceApprovalModel.eXuldAPPNO = 0;
      _requestInsuranceApprovalModel.projectID = 0;
    }
    _insuranceApproval.clear();
    _insuranceApproval.length = 0;

    await baseAppClient.post(GET_PAtIENTS_INSURANCE_APPROVALS, onSuccess: (dynamic response, int statusCode) {
      response['HIS_Approval_List'].forEach((item) {
        _insuranceApproval.add(InsuranceApprovalModel.fromJson(item));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: _requestInsuranceApprovalModel.toJson());
  }

  Future getFamilyFiles() async {
    var myFamily = await sharedPref.getObject(FAMILY_FILE);
    if (myFamily != null) {
      getAllSharedRecordsByStatusResponse = GetAllSharedRecordsByStatusResponse.fromJson(myFamily);
    } else {
      getSharedRecordByStatus();
    }
  }

  Future getSharedRecordByStatus() async {
    var myFamily = await sharedPref.getObject(FAMILY_FILE);
    if (myFamily != null) {
      getAllSharedRecordsByStatusResponse = GetAllSharedRecordsByStatusResponse.fromJson(myFamily);
      return Future.value(GetAllSharedRecordsByStatusResponse.fromJson(myFamily));
    } else {
      try {
        dynamic localRes;
        var request = GetAllSharedRecordsByStatusReq();
        request.status = 0;
        await baseAppClient.post(GET_SHARED_RECORD_BY_STATUS, onSuccess: (dynamic response, int statusCode) {
          localRes = response;
        }, onFailure: (String error, int statusCode) {
          AppToast.showErrorToast(message: error);
          throw error;
        }, body: request.toJson());
        sharedPref.setObject(FAMILY_FILE, localRes);
        getAllSharedRecordsByStatusResponse = GetAllSharedRecordsByStatusResponse.fromJson(localRes);
      } catch (error) {
        print("------------"+error.toString());
        throw error;
      }
    }
  }

  Future getInsuranceDetails(data) async {
    dynamic localRes;
    await baseAppClient.post(
      INSURANCE_DETAILS,
      onSuccess: (dynamic response, int statusCode) {
        localRes = response['List_InsuranceCheckList'];
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: {'CompanyID': data.companyID, 'SubCategoryID': data.subCategoryID},
    );
    return Future.value(localRes);
  }

  Future getPatientInsuranceDetails({String? setupID, int? projectID, String? patientIdentificationID, int? patientID, bool? isFamily, int parentID = 0}) async {
    error = "";
    hasError = false;
    insuranceCardDetails = null;
    isHaveInsuranceCard = false;
    await baseAppClient.post(
      GET_PATIENT_INSURANCE_DETAILS,
      onSuccess: (dynamic response, int statusCode) {
        insuranceCardDetailsList.clear();
        isHaveInsuranceCard = true;
        response['List_PatientInsuranceDetails'].forEach((item) {
          insuranceCardDetailsList.add(InsuranceCardDetailsModel.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: {
        'SetupID': setupID,
        'ProjectID': projectID,
        'PatientIdentificationID': patientIdentificationID,
        'isDentalAllowedBackend': false,
        'PatientID': patientID,
        'IsFamily': isFamily,
        'ParentID': parentID
      },
    );
  }

  Future getInsuranceSchemes(int projectID, int companyID) async {
    dynamic localRes;
    await baseAppClient.post(
      INSURANCE_SCHEMES,
      onSuccess: (dynamic response, int statusCode) {
        localRes = response['PatientER_SchemesOfAactiveCompaniesGetList'];
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: {'CompanyID': companyID, 'ProjectID': projectID},
    );
    return Future.value(localRes);
  }

  Future submitManualInsuranceUpdateRequest(InsuranceManualUpdateRequest insuranceManualUpdateRequest) async {
    dynamic localRes;
    await baseAppClient.post(
      UPDATE_MANUAL_INSURANCE,
      onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: insuranceManualUpdateRequest.toJson(),
    );
    return Future.value(localRes);
  }

  Future getInsuranceCompanies() async {
    dynamic localRes;
    await baseAppClient.post(
      INSURANCE_COMPANIES,
      onSuccess: (dynamic response, int statusCode) {
        localRes = response['PatientER_InsuranceCompanyGetList'];
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: {},
    );
    return Future.value(localRes);
  }

  Future uploadInsuranceCard(BuildContext context, {String? patientIdentificationID, int? patientID, String image = ""}) async {
    error = "";
    Map<String, dynamic> body = Map();
    body['PatientID'] = patientID;
    body['PatientType'] = user.patientType;
    body['MobileNo'] = user.mobileNumber;
    body['PatientIdentificationID'] = patientIdentificationID;
    body['InsuranceCardImage'] = image;

    dynamic localRes;

    await baseAppClient.post(
      UPLOAD_INSURANCE_CARD,
      onSuccess: (dynamic response, int statusCode) {
        print(response);
        if (response['MessageStatus'] == 1) {
          AppToast.showSuccessToast(message: TranslationBase.of(context).requestSent);
        } else {
          AppToast.showErrorToast(message: response['ErrorEndUserMessage']);
        }
        localRes = response;
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
        throw error;
      },
      body: body,
    );
    return Future.value(localRes);
  }
}
