import {
	bankLoginProviderList,
	createBankLoginCheckoutContext,
	createBankLoginClassicPayloadContext,
	getBankLoginProviderByMethod,
} from '@greenpay/bank-login'
import { PaymentSelectors } from '@greenpay/redux'
import { usePaymentSelect, useValidationDispatch } from '@greenpay/redux'
import { useEffect } from '@wordpress/element'
import { useSelect } from '@wordpress/data'

const ClassicPayloadComponent: React.FC = () => {
	const method = useSelect((select) => (select('green-pay/payment') as PaymentSelectors).getMethod(), [])
	const debit = useSelect((select) => (select('green-pay/payment') as PaymentSelectors).getDebit(), [])
	const payment = usePaymentSelect()
	const { validatePlaid, validateRibbit } = useValidationDispatch()

	useEffect(() => {
		const setValue = (name: string, value: string) => {
			const input = document.querySelector<HTMLInputElement>(`input[name="${name}"]`)
			if (input) {
				input.value = value
			}
		}

		const checkoutContext = createBankLoginCheckoutContext(payment, {
			validatePlaid,
			validateRibbit,
		})
		const payloadContext = createBankLoginClassicPayloadContext(checkoutContext, setValue)

		setValue('wc_greenpay_context', 'classic')
		if (method) {
			setValue('wc_greenpay_payment_method', method)
		}

		bankLoginProviderList.forEach((provider) => provider.clearClassicPayload(payloadContext))

		const bankLoginProvider = getBankLoginProviderByMethod(method)
		if (bankLoginProvider) {
			bankLoginProvider.syncClassicPayload(payloadContext)
		}

		setValue('wc_greenpay_routing_number', method === 'debit' ? debit?.routingNumber ?? '' : '')
		setValue('wc_greenpay_account_number', method === 'debit' ? debit?.accountNumber ?? '' : '')
	}, [method, debit, payment, validatePlaid, validateRibbit])

	return null
}

export default ClassicPayloadComponent
