import { useEffect, useRef, useState } from 'react' import apiFetch from '@wordpress/api-fetch' import { useDispatch } from '@wordpress/data' import { __ } from '@wordpress/i18n' import { FormComponentConstructor } from '../../lib/types' import { FormFieldProps } from '../../types' import { useField } from '../../lib/hooks/useField' import { useForm } from '../../lib/FormProvider' import { store } from '../../../../../store/backend' import { applyWhatsAppTokenValidation } from '../WhatsAppValidateField/applyTokenValidation' import { WHATSAPP_CREDENTIALS_UPDATED_EVENT } from '../WhatsAppValidateField/types' import { WhatsAppAuthData } from './types' import './WhatsAppAuthField.scss' const BUSINESS_ACCOUNT_FIELD = 'wbk_whatsapp_business_account_id' const PHONE_NUMBER_FIELD = 'wbk_whatsapp_phone_number_id' export const createWhatsAppAuthField: FormComponentConstructor = ({ field, }) => { return ({ misc }: FormFieldProps) => { const form = useForm() const { value, setValue } = useField(field) const { removeWhatsAppAuth, setFieldOptions, setToastNotification } = useDispatch(store) const [isLoading, setIsLoading] = useState(false) const [internalError, setInternalError] = useState(false) const [statusMessage, setStatusMessage] = useState(null) const validatedTokenRef = useRef('') useEffect(() => { let cancelled = false const loadAuthData = async () => { try { const data = (await apiFetch({ path: '/wbk/v2/whatsapp-auth-data/', })) as WhatsAppAuthData if (cancelled) { return } setInternalError(Boolean(data?.internalError)) if (data?.isAuthenticated && data.access_token) { setValue(data.access_token) } } catch (error) { if (!cancelled) { setInternalError(true) } } } loadAuthData() return () => { cancelled = true } }, [setValue]) useEffect(() => { const accessToken = String(value || '').trim() if ( accessToken === '' || validatedTokenRef.current === accessToken ) { return } validatedTokenRef.current = accessToken setStatusMessage(null) const validateConnectedAccount = async () => { try { const result = await applyWhatsAppTokenValidation({ accessToken, form, setFieldOptions, }) if (!result.success) { setStatusMessage(result.message) } } catch (error: any) { setStatusMessage( error?.message || __( 'Failed to load WhatsApp business accounts.', 'webba-booking-lite' ) ) } } validateConnectedAccount() }, [form, setFieldOptions, value]) const handleConnect = async () => { setIsLoading(true) setStatusMessage(null) try { const data = (await apiFetch({ path: '/wbk/v2/whatsapp-auth-data/', })) as WhatsAppAuthData if (data?.authUrl) { window.location.href = data.authUrl return } setInternalError(true) } catch (error) { setInternalError(true) } finally { setIsLoading(false) } } const handleDisconnect = async () => { setIsLoading(true) setStatusMessage(null) try { await removeWhatsAppAuth() setValue('') validatedTokenRef.current = '' setInternalError(false) if (form.fields[BUSINESS_ACCOUNT_FIELD]) { form.fields[BUSINESS_ACCOUNT_FIELD].setValue('') } if (form.fields[PHONE_NUMBER_FIELD]) { form.fields[PHONE_NUMBER_FIELD].setValue('') } if (typeof window !== 'undefined') { window.dispatchEvent( new CustomEvent(WHATSAPP_CREDENTIALS_UPDATED_EVENT, { detail: { businessAccountId: '', phoneNumberId: '', }, }) ) } setToastNotification({ type: 'success', message: __( 'WhatsApp disconnected.', 'webba-booking-lite' ), }) } finally { setIsLoading(false) } } const isAuthorized = String(value || '') !== '' return (
{internalError && !isAuthorized ? ( {__( 'Unable to reach Webba Connect. Please try again later.', 'webba-booking-lite' )} ) : ( )}
{statusMessage && (

{statusMessage}

)} {misc?.description && (

{misc.description}

)}
) } }