import {axios, withStore } from '../../services/AxiosInstance'

import { PatientRegistrationActionTypes } from './patient.action.types'
import {METADATA_END_POINTS} from '../helpers/action-urls'
import {MettaSvr_Common} from '../helpers/action-enums'

// register user state changes
const postPatientStart = () => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_START
})


const postPatientSuccess = response => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_SUCCESS,
    payload: response
})

export const postPatientFailure = err => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_FAILURE,
    payload: err
})

export const setPatientRegistrationCurrentPage = (pageNum) => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_PAGE_CHANGE,
    payload: pageNum
})

export const clearPatientRegistrationState = () => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_CLEAR_STATE
})

export const startPatientSubscriptionRenewal = () => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_RENEW_SUBSCRIPTION_START
})

export const successPatientSubscriptionRenewal= (response) => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_RENEW_SUBSCRIPTION_SUCCESS,
    payload: response

})
export const startPatientRegistrationPayment = () => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_PAYMEMT_START
})

export const successPatientRegistrationPayment = (payment) => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_PAYMEMT_SUCCESS,
    payload: payment

})

export const cancelPatientRegistrationPayment = () => ({
    type: PatientRegistrationActionTypes.CANCEL_PATIENT_PAYMEMT,    
})
export const failedPatientRegistrationPayment = (err) => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_PAYMEMT_FAILURE,
    payload: err
})

const patientRegistrationAndPaymentCompleted = (response) => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_REGISTRATION_PAYMEMT_COMPLETE,
    payload: response
})

export const patientRegistrationClearState = () =>({
    type: PatientRegistrationActionTypes.RESET_STATE,    
})
/**
 * validation of subscription codes 
 */

const postPatientValidateSubscriptionCodeStart = () => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_SUBSCODE_VALIDATION_START
})


const postPatientValidateSubscriptionCodeSuccess = response => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_SUBSCODE_VALIDATION_SUCCESS,
})

const postPatientValidateSubscriptionCodeFailure = err => ({
    type: PatientRegistrationActionTypes.POST_PATIENT_SUBSCODE_VALIDATION_FAILURE,
    payload: err
})


export const validateSubscriptionCodeAsync = (body) => {
    return async dispatch => {
        dispatch(postPatientValidateSubscriptionCodeStart())
        try {
            const {API_VERSION_V1, VALIDATE_SUBSCRIPTION_CODE} = METADATA_END_POINTS.auth
            const response = await axios.post(API_VERSION_V1 + VALIDATE_SUBSCRIPTION_CODE, body)
            const {apiResponseStatus, errorMessage, result} = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(postPatientValidateSubscriptionCodeFailure({message: errorMessage}))
            }else if(result === false) {
                dispatch(postPatientValidateSubscriptionCodeFailure({message: "invalid subscription code or not available"}))
            }
            else{
                // dispatch(postPatientValidateSubscriptionCodeFailure({message: "mock error"}))
                dispatch(postPatientValidateSubscriptionCodeSuccess())
            }
        } catch (ex) {
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(postPatientValidateSubscriptionCodeFailure({message: ex.response.data.title ?? ex.message, apiResponseStatus: -1}))
        }
    }
}

export const registerPatientAsync = (body) => {
    return async dispatch => {
        dispatch(postPatientStart())
        try{

            // dispatch(postUserFailure(testErroObject()))
            // dispatch(postUserSuccess(testSuccessObject()))

            // return
            const {API_VERSION_V1, REGISTER_ENDPOINT} = METADATA_END_POINTS.auth
            const response = await axios.post(API_VERSION_V1 + REGISTER_ENDPOINT, body)
            const {apiResponseStatus, errorMessage, result} = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(postPatientFailure({message: errorMessage}))
            }else{
                dispatch(postPatientSuccess(result))
            }
        }catch(ex){
            // debugger
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(postPatientFailure({message: ex.response.data.title ?? ex.message, apiResponseStatus: -1}))
        }
    }
}

export const registrationPaymentCapture = (body) => {
    return async dispatch => {
        try{
            // dispatch(postPatientFailure(testErroObject()))
            // dispatch(patientRegistrationAndPaymentCompleted(testSuccessObject()))

            // return
            const {API_VERSION_V1, PAYMENT_CAPTURE_ENDPOINT} = METADATA_END_POINTS.auth
            const response = await axios.post(API_VERSION_V1 + PAYMENT_CAPTURE_ENDPOINT, body)
            const {apiResponseStatus, errorMessage, result} = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(postPatientFailure({message: errorMessage, apiResponseStatus}))
            }else{
                console.log(`payment capture successful = ${result}`)
                dispatch(patientRegistrationAndPaymentCompleted(result))
            }
        }catch(ex){
            // debugger
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(postPatientFailure({message: ex.response.data.title ?? ex.message, apiResponseStatus: -1}))
        }
    }
}

export const renewSubscriptionAsync = (body) => {
    return async (dispatch, getState) => {

        try{
            dispatch(startPatientSubscriptionRenewal())
            const {user} = getState()                

            // return
            const {API_VERSION_V1, RENEW_SUBSCRIPTION_CODE} = METADATA_END_POINTS.auth
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(API_VERSION_V1 + RENEW_SUBSCRIPTION_CODE, body)
            const {apiResponseStatus, errorMessage, result} = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(postPatientFailure({message: errorMessage, apiResponseStatus}))
            }else{
                console.log(`payment capture successful = ${result}`)
                const outputResponse = {
                    userID: user.currentUser.userId,
                    orderDetail: result
                }
                dispatch(successPatientSubscriptionRenewal(outputResponse))
            }
        }catch(ex){
            // debugger
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(postPatientFailure({message: ex.response.data.title ?? ex.message, apiResponseStatus: -1}))
        }
    }
}
/*
const testErroObject = () => ({message: 'very serious erorr 400!!'})
const testSuccessObject = () => (
    {
        "result": "d15238db-44ef-4804-804a-9ed8eb9d1966",
        "orderDetails": {
            "orderId": "abcd",
            "razorpayKey": "abcd",
            "amount": 20000.0,
            "currency": "INR",
            "name": "MR Test User",
            "email": "some1@test.com",
            "contactNumber": 123456,
            "address": "1 bye 2 jadav pur, City-kolkata, State-Westbengal, PinCode-12345, Country-India",
            "description": "Payment initiated for user with ID 31"
        },
        "apiResponseStatus": 3,
        "errorMessage": null
    }
)
const testCheckPaymentVerified = () => ({
    "result": true,
    "orderDetails": null,
    "apiResponseStatus": 3,
    "errorMessage": null
})
*/