import { PaymentSelectors, ValidationSelectors, usePaymentDispatch, useValidationDispatch } from '@greenpay/redux'

import { checkRibbitBankTan, getCheckoutBillingDetails, showRibbitError, validateRibbitSessionBilling } from '@greenpay/utils'

import { Button, CircularProgress, Divider, IconButton, Paper, Typography } from '@mui/material'

import AccountBalanceIcon from '@mui/icons-material/AccountBalance'

import CheckCircleIcon from '@mui/icons-material/CheckCircle'

import { useSelect } from '@wordpress/data'

import { useEffect, useLayoutEffect, useState } from '@wordpress/element'

import TanFlow from '../Plaid/TanFlow'

import RibbitWidget from './RibbitWidget'



import styles from './Ribbit.module.scss'



const RibbitComponent: React.FC = () => {

	const ribbit = useSelect((select) => (select('green-pay/payment') as PaymentSelectors).getRibbit(), [])

	const debit = useSelect((select) => (select('green-pay/payment') as PaymentSelectors).getDebit(), [])

	const accountMask = useSelect((select) => (select('green-pay/payment') as PaymentSelectors).getAccountMask(), [])

	const tanStatus = useSelect((select) => (select('green-pay/validation') as ValidationSelectors).getTanStatus(), [])



	const { setMethod, setDebit, setAccountMask } = usePaymentDispatch()

	const { setPlaidError, setPlaidTouched } = useValidationDispatch()



	const [showWidget, setShowWidget] = useState(false)

	const [bankLoginBusy, setBankLoginBusy] = useState(false)



	useLayoutEffect(() => {

		if (!ribbit) return



		if (!ribbit.success) {

			const message = 'Bank login was unsuccessful, please try again.'

			setPlaidTouched(true)

			setPlaidError(message)

			showRibbitError(message)

			return

		}



		if (ribbit.isTAN && !tanStatus) {

			setPlaidTouched(true)

			setPlaidError('Bank account requires additional user verification.')

			return

		}



		if (ribbit.success && !ribbit.isTAN) {

			setAccountMask(ribbit.accountMask ?? '')

			setMethod('ribbit')

			setPlaidError('')

		}

	}, [ribbit, tanStatus, setPlaidTouched, setPlaidError, setMethod, setAccountMask])



	useEffect(() => {

		if (!tanStatus || !debit) return



		setPlaidError('')

		setMethod('debit')

		if (debit.accountNumber) {

			setAccountMask(debit.accountNumber.slice(-4))

			setDebit(debit)

		}

	}, [tanStatus, debit, setPlaidError, setMethod, setDebit, setAccountMask])



	const handleWidget = (widgetVisible: boolean) => {

		setShowWidget(widgetVisible)

	}



	const handleError = (message: string) => {

		setPlaidTouched(true)

		setPlaidError(message)

		showRibbitError(message)

	}



	const handleBankLoginClick = () => {

		const billing = getCheckoutBillingDetails()

		const validation = validateRibbitSessionBilling(billing)



		if (!validation.valid) {

			setPlaidTouched(true)

			setPlaidError(validation.message)

			showRibbitError(validation.message)

			return

		}



		setPlaidError('')

		setPlaidTouched(false)

		setShowWidget(true)

	}



	if (ribbit && ribbit.isTAN && !tanStatus) {

		return <TanFlow institution={ribbit.institutionName} helpLink={ribbit.helpLink} />

	}



	if (!ribbit || !ribbit.success) {

		return (

			<Paper className={styles['button-container']} variant="outlined">

				<Typography sx={{ fontSize: '0.8rem' }}>Click to securely log in to your bank account</Typography>

				<Button

					variant="contained"

					color="primary"

					size="large"

					fullWidth

					onClick={handleBankLoginClick}

					disabled={showWidget || bankLoginBusy}

					className={styles.button}

					startIcon={

						showWidget || bankLoginBusy ? (

							<CircularProgress className={styles.loader} size="20px" />

						) : (

							<AccountBalanceIcon className={styles.logo} />

						)

					}

				>

					Bank Login

				</Button>

				<RibbitWidget

					showWidget={showWidget}

					onWidget={handleWidget}

					onError={handleError}

					onBusyChange={setBankLoginBusy}

				/>

			</Paper>

		)

	}



	return (

		<Paper variant="outlined" className={styles['confirm-container']}>

			<div className={styles.title}>Bank account</div>

			<Divider className={styles.divider} />

			<Paper variant="outlined" className={styles['confirm-inner']}>

				<IconButton disabled={true} size="large">

					<AccountBalanceIcon />

				</IconButton>

				<div className={styles.spacer}>

					<div className={styles.title}>{ribbit.institutionName}</div>

					{(ribbit.accountMask || accountMask) && (

						<div>Account ending in {ribbit.accountMask || accountMask}</div>

					)}

				</div>

				<div className={styles['icon-container']}>

					<CheckCircleIcon className={styles['success-icon']} />

				</div>

			</Paper>

		</Paper>

	)

}



export default RibbitComponent


