import { forwardRef, useState, useCallback } from 'react'; import { Box, Divider, Theme, useMediaQuery } from '@mui/material'; import { PublicRouting, RouteResult } from '../../api/routing/types'; import { handleRouting } from '../../api/routing'; import { InjectLeadContext, useInjectLead } from '../../api/deals/hooks'; import { useWidgetStateContext } from '../../state'; import PersonalInfoForm from './PersonalInfoForm'; import RoutingResultForm from './RoutingResultForm'; import { FormValues, FormScreenStatus, PersonalInfoFormStatus } from './types'; function convertFormAnswersToRoutingParams( answers: Record ): { questionId: number; answerId: number }[] { return Object.entries(answers) .filter((entry) => entry[1] > 0) // Filter out answers that are not selected .map(([questionId, answerId]) => ({ questionId: parseInt(questionId, 10), answerId, })); } const FormScreen = forwardRef( ({ routing, productId }, ref) => { const isMobile = useMediaQuery((theme) => theme.breakpoints.down('md')); const [, onError] = useWidgetStateContext(); const [status, setStatus] = useState('personal-info'); // This stores the furthest stage the user has reached in the personal info form. Once a stage is reached, the user can't go back to a previous stage. // Basically, we don't want to hide the name, phone, or questions once they are visible. const [personalInfoFormStatus, setPersonalInfoFormStatus] = useState([ 'initial', ]); // This is called here so that the returned lead data isn't lost when the user moves to the calendar form. const injectLead = useInjectLead(routing.uuid, productId, onError); const [formValues, setFormValues] = useState(null); const [routeResult, setRouteResult] = useState(null); const moveToCalendar = useCallback( async (values: FormValues | null, err?: string) => { if (err || !values) { onError(err || 'Missing values'); return; } try { setFormValues(values); const result = await handleRouting({ routingId: routing.uuid, email: values.email, answers: convertFormAnswersToRoutingParams(values.answers), }); setRouteResult(result); setStatus('calendar'); } catch (e) { onError(e as Error); } }, [onError, routing.uuid] ); const moveToPersonalInfo = useCallback(() => { setStatus('personal-info'); }, []); return ( ({ height: 1, overflow: 'hidden', [theme.breakpoints.up('md')]: { display: 'grid', gridTemplateColumns: '1fr auto 1fr', '& > .MuiBox-root': { p: `${theme.spacing(4)} !important`, }, }, '& > .MuiBox-root': { height: 1, overflow: 'auto', p: 3, }, })} > {!isMobile && } ); } ); FormScreen.displayName = 'FormScreen'; export default FormScreen;