import { useEffect, useState } from 'react' import apiFetch from '@wordpress/api-fetch' import { __ } from '@wordpress/i18n' import classNames from 'classnames' import { FormComponentConstructor } from '../../lib/types' import { FormFieldProps } from '../../types' import { useForm } from '../../lib/FormProvider' import TimedLink from '../../../common/TimedLink/TimedLink' import warningIcon from '../../../../../../public/images/warning-icon.png' import successIcon from '../../../../../../public/images/succesessful-icon.png' import './GmailAuthField.scss' interface GmailAuthData { isAuthenticated?: boolean internalError?: boolean authUrl?: string | null revokeUrl?: string | null email?: string } export const createGmailAuthField: FormComponentConstructor = () => { return ({ label, misc }: FormFieldProps) => { const form = useForm() const [authData, setAuthData] = useState(null) const [isLoading, setIsLoading] = useState(true) useEffect(() => { let cancelled = false setIsLoading(true) apiFetch({ path: '/wbk/v2/get-gmail-auth-data/', }) .then((result: any) => { if (!cancelled) { setAuthData(result || {}) } }) .catch(() => { if (!cancelled) { setAuthData({ isAuthenticated: false, internalError: true, }) } }) .finally(() => { if (!cancelled) { setIsLoading(false) } }) return () => { cancelled = true } }, []) useEffect(() => { const email = String(authData?.email || '').trim() if (!email || !authData?.isAuthenticated) { return } const fromEmailField = form.fields.wbk_from_email if (fromEmailField && fromEmailField.value.value !== email) { fromEmailField.setValue(email) } }, [authData, form.fields.wbk_from_email]) const isAuthenticated = Boolean(authData?.isAuthenticated) const internalError = Boolean(authData?.internalError) const authUrl = authData?.authUrl || '' const revokeUrl = authData?.revokeUrl || '' return (
{label && (
{label}
)}
{isLoading || authData === null ? (
{__('Loading...', 'webba-booking-lite')}
) : (
{ {isAuthenticated ? __( 'Authorized', 'webba-booking-lite' ) : internalError ? __( 'Internal error', 'webba-booking-lite' ) : __( 'Not authorized', 'webba-booking-lite' )}
{!isAuthenticated && !internalError && authUrl && ( {__('Authorize', 'webba-booking-lite')} )} {!isAuthenticated && internalError && (
{__( 'Internal error occurred. Please try again later.', 'webba-booking-lite' )}
)} {isAuthenticated && revokeUrl && ( {__( 'Remove authorization', 'webba-booking-lite' )} )}
)}
{misc?.description && (

{misc.description}

)}
) } }