import RibbitComponent from '../../components/Ribbit/Ribbit'
import { Ribbit } from '@greenpay/models'
import { BankLoginCheckoutContext, BankLoginClassicPayloadContext, IBankLoginProvider } from './types'

export const ribbitBankLoginProvider: IBankLoginProvider = {
	id: 'ribbit',
	Component: RibbitComponent,
	resolveState(ctx: BankLoginCheckoutContext): Ribbit | null {
		const ribbitState = ctx.getRibbit()
		const fallbackCustomerToken = ctx.getHiddenInputValue('wc_greenpay_customer_token')
		const fallbackAccountToken = ctx.getHiddenInputValue('wc_greenpay_account_token')
		const fallbackInstitution = ctx.getHiddenInputValue('wc_greenpay_institution')

		return (
			ribbitState ??
			(fallbackCustomerToken && fallbackAccountToken && fallbackInstitution
				? {
						customerToken: fallbackCustomerToken,
						accountToken: fallbackAccountToken,
						institutionName: fallbackInstitution,
						accountMask: '',
						success: true,
						isTAN: false,
					}
				: null)
		)
	},
	validate(ctx: BankLoginCheckoutContext): boolean {
		return ctx.validateRibbit(this.resolveState(ctx))
	},
	buildPaymentMethodData(ctx: BankLoginCheckoutContext) {
		const ribbit = this.resolveState(ctx)
		return {
			payment_method: this.id,
			customer_token: ribbit?.customerToken,
			account_token: ribbit?.accountToken,
			institution: ribbit?.institutionName,
		}
	},
	syncClassicPayload(ctx: BankLoginClassicPayloadContext) {
		const ribbit = this.resolveState(ctx)
		ctx.setValue('wc_greenpay_customer_token', ribbit?.customerToken ?? '')
		ctx.setValue('wc_greenpay_account_token', ribbit?.accountToken ?? '')
		ctx.setValue('wc_greenpay_institution', ribbit?.institutionName ?? '')
	},
	clearClassicPayload(ctx: BankLoginClassicPayloadContext) {
		ctx.setValue('wc_greenpay_customer_token', '')
		ctx.setValue('wc_greenpay_account_token', '')
		ctx.setValue('wc_greenpay_institution', '')
	},
}
