import { useEffect, useMemo, useReducer, useRef, useState } from 'react';
import { Banner, Button, Checkbox, CurrencyInput, FieldGroup, Grid, Input, Modal, MultiStepForm, Option, RadioButton, RadioButtonGroup, Select, TextArea, useModalContext, useToaster } from '@pega/cosmos-react-core';
import { loadingTimeoutMS } from '../Progress/Progress.mocks';
export const stepFields = [
    [
        { name: 'firstName', label: 'First name' },
        { name: 'lastName', label: 'Last name' },
        { name: 'currentTitle', label: 'Current title' },
        { name: 'currentCompany', label: 'Current company' },
        { name: 'salaryRequested', label: 'Salary requested' },
        { name: 'experienceLevel', label: 'Experience level' },
        { name: 'priorityOne', label: 'First' },
        { name: 'priorityTwo', label: 'Second' },
        { name: 'priorityThree', label: 'Third' }
    ],
    [
        { name: 'interviewNotes', label: 'Impressions' },
        { name: 'additionalInterview', label: 'Request additional interview' }
    ],
    [{ name: 'nextInterviewer', label: 'Next interviewer' }],
    [
        { name: 'salaryRequestedReview', label: 'Salary requested' },
        { name: 'salaryRequestReview', label: 'Salary request fit' },
        { name: 'cultureFit', label: 'Culture fit' },
        { name: 'finalRecommendation', label: 'Final recommendation' },
        { name: 'recommendationComments', label: 'Comments' }
    ]
];
export const initialState = {
    currentStepIndex: 0,
    cancelled: false,
    finished: false,
    numSteps: 3,
    formData: {
        firstName: 'Marcus',
        lastName: 'Kennedy',
        currentTitle: 'Data Analyst',
        currentCompany: 'Acme Co.'
    },
    formErrors: {}
};
const formValidation = {
    salaryRequested: {
        message: 'This field is required.',
        validator: (value) => value?.length > 0
    },
    experienceLevel: {
        message: 'This field is required.',
        validator: (value) => value?.length > 0
    },
    nextInterviewer: {
        message: 'This field is required.',
        validator: (value) => value?.length > 0
    },
    salaryRequestReview: {
        message: 'This field is required.',
        validator: (value) => value?.length > 0
    },
    cultureFit: {
        message: 'This field is required.',
        validator: (value) => value?.length > 0
    },
    finalRecommendation: {
        message: 'This field is required.',
        validator: (value) => value?.length > 0
    }
};
export const reducer = (state, action) => {
    switch (action.type) {
        case 'restart': {
            return initialState;
        }
        case 'cancel': {
            return {
                ...state,
                cancelled: true
            };
        }
        case 'finish': {
            return {
                ...state,
                finished: true
            };
        }
        case 'setStep': {
            return {
                ...state,
                currentStepIndex: action.payload,
                formErrors: {}
            };
        }
        case 'setFieldValue': {
            const { name: field, label, value } = action.payload;
            const formData = {
                ...state.formData
            };
            const formErrors = {
                ...state.formErrors
            };
            formData[field] = value;
            if (formErrors[field] && Object.hasOwn(formValidation, field)) {
                const valid = formValidation[field].validator(value);
                if (valid) {
                    delete formErrors[field];
                }
                else {
                    formErrors[field] = { label, description: formValidation[field].message };
                }
            }
            return {
                ...state,
                formData,
                formErrors
            };
        }
        case 'submitCurrentStep': {
            const stepIndex = state.numSteps === 4 || state.currentStepIndex <= 1
                ? state.currentStepIndex
                : state.currentStepIndex + 1;
            const formErrors = { ...state.formErrors };
            let isValid = true;
            const validateFields = (fields) => {
                if (!fields)
                    return;
                fields.forEach(({ name: field, label }) => {
                    if (Object.hasOwn(formValidation, field)) {
                        const valid = formValidation[field].validator(state.formData[field]);
                        if (valid) {
                            delete formErrors[field];
                        }
                        else {
                            isValid = false;
                            formErrors[field] = { label, description: formValidation[field].message };
                        }
                    }
                });
            };
            validateFields(stepFields[stepIndex]);
            return {
                ...state,
                numSteps: state.formData.additionalInterview ? 4 : 3,
                currentStepIndex: isValid && state.currentStepIndex !== state.numSteps - 1
                    ? state.currentStepIndex + 1
                    : state.currentStepIndex,
                finished: isValid && state.currentStepIndex === state.numSteps - 1,
                formErrors
            };
        }
        default:
            return state;
    }
};
export const ApplicantDetailsFields = ({ formData, formErrors, dispatch }) => {
    return (<Grid container={{ gap: 1, cols: 'repeat(2, minmax(0, 1fr))' }}>
      <Input {...stepFields[0][0]} value={formData.firstName} readOnly/>
      <Input {...stepFields[0][1]} value={formData.lastName} readOnly/>
      <Input {...stepFields[0][2]} value={formData.currentTitle} onChange={(e) => dispatch({
            type: 'setFieldValue',
            payload: { ...stepFields[0][2], value: e.target.value }
        })}/>
      <Input {...stepFields[0][3]} value={formData.currentCompany} onChange={(e) => dispatch({
            type: 'setFieldValue',
            payload: { ...stepFields[0][3], value: e.target.value }
        })}/>
      <CurrencyInput {...stepFields[0][4]} value={formData.salaryRequested} currencyISOCode='USD' onChange={value => dispatch({
            type: 'setFieldValue',
            payload: { ...stepFields[0][4], value }
        })} status={formErrors.salaryRequested ? 'error' : undefined} info={formErrors.salaryRequested ? formErrors.salaryRequested.description : undefined} required/>
      <Select {...stepFields[0][5]} value={formData.experienceLevel} onChange={(e) => {
            dispatch({
                type: 'setFieldValue',
                payload: { ...stepFields[0][5], value: e.target.value }
            });
        }} status={formErrors.experienceLevel ? 'error' : undefined} info={formErrors.experienceLevel ? formErrors.experienceLevel.description : undefined} required>
        <Option value=''>--</Option>
        <Option value='junior'>0-3 years (junior)</Option>
        <Option value='mid-level'>4-6 years (mid)</Option>
        <Option value='senior'>7-10 years (senior)</Option>
        <Option value='expert'>10+ years (expert)</Option>
      </Select>
      <Grid item={{ colStart: '1', colEnd: '-1' }}>
        <FieldGroup name='Work priorities' headingTag='h3'>
          <Grid container={{ gap: 1, cols: 'repeat(3, minmax(0, 1fr))' }}>
            <Input {...stepFields[0][6]} value={formData.priorityOne} onChange={(e) => {
            dispatch({
                type: 'setFieldValue',
                payload: { ...stepFields[0][6], value: e.target.value }
            });
        }}/>
            <Input {...stepFields[0][7]} value={formData.priorityTwo} onChange={(e) => {
            dispatch({
                type: 'setFieldValue',
                payload: { ...stepFields[0][7], value: e.target.value }
            });
        }}/>
            <Input {...stepFields[0][8]} value={formData.priorityThree} onChange={(e) => {
            dispatch({
                type: 'setFieldValue',
                payload: { ...stepFields[0][8], value: e.target.value }
            });
        }}/>
          </Grid>
        </FieldGroup>
      </Grid>
    </Grid>);
};
export const InterviewNotesFields = ({ formData, formErrors, dispatch }) => {
    return (<Grid container={{ gap: 1, cols: '1fr' }}>
      <TextArea {...stepFields[1][0]} value={formData.interviewNotes} onChange={(e) => {
            dispatch({
                type: 'setFieldValue',
                payload: { ...stepFields[1][0], value: e.target.value }
            });
        }} status={formErrors.impressions ? 'error' : undefined} info={formErrors.impressions ? formErrors.impressions.description : undefined}/>
      <Checkbox {...stepFields[1][1]} defaultChecked={formData.additionalInterview} onChange={(e) => {
            dispatch({
                type: 'setFieldValue',
                payload: { ...stepFields[1][1], value: e.target.checked }
            });
        }}/>
    </Grid>);
};
export const NextInterviewFields = ({ formData, formErrors, dispatch }) => {
    return (<Select {...stepFields[2][0]} value={formData.nextInterviewer} onChange={(e) => {
            dispatch({
                type: 'setFieldValue',
                payload: { ...stepFields[2][0], value: e.target.value }
            });
        }} status={formErrors.nextInterviewer ? 'error' : undefined} info={formErrors.nextInterviewer ? formErrors.nextInterviewer.description : undefined} required>
      <Option value=''>Choose an option...</Option>
      <Option>Myself</Option>
      <Option>Cindy Turner </Option>
      <Option>Seth DeAngelo</Option>
      <Option>Janet Moore</Option>
    </Select>);
};
export const RecommendationsFields = ({ formData, formErrors, dispatch }) => {
    return (<Grid container={{ gap: 1, cols: '1fr' }}>
      <CurrencyInput {...stepFields[3][0]} value={formData.salaryRequested} onChange={() => { }} currencyISOCode='USD' readOnly/>

      <p>$99,000 is the recommended salary for this position.</p>

      <RadioButtonGroup {...stepFields[3][1]} onChange={(e) => {
            dispatch({
                type: 'setFieldValue',
                payload: {
                    ...stepFields[3][1],
                    value: e.target.value
                }
            });
        }} status={formErrors.salaryRequestReview ? 'error' : undefined} info={formErrors.salaryRequestReview ? formErrors.salaryRequestReview.description : undefined} inline required>
        <RadioButton label='Very low' id='salaryTargetVeryLow' value='salaryTargetVeryLow' checked={formData.salaryRequestReview === 'salaryTargetVeryLow'}/>
        <RadioButton label='Low' id='salaryTargetLow' value='salaryTargetLow' checked={formData.salaryRequestReview === 'salaryTargetLow'}/>
        <RadioButton label='On trend' id='salaryTargetOnTrend' value='salaryTargetOnTrend' checked={formData.salaryRequestReview === 'salaryTargetOnTrend'}/>
        <RadioButton label='High' id='salaryTargetHigh' value='salaryTargetHigh' checked={formData.salaryRequestReview === 'salaryTargetHigh'}/>
        <RadioButton label='Very high' id='salaryTargetVeryHigh' value='salaryTargetVeryHigh' checked={formData.salaryRequestReview === 'salaryTargetVeryHigh'}/>
      </RadioButtonGroup>

      <RadioButtonGroup {...stepFields[3][2]} onChange={(e) => {
            dispatch({
                type: 'setFieldValue',
                payload: {
                    ...stepFields[3][2],
                    value: e.target.value
                }
            });
        }} status={formErrors.cultureFit ? 'error' : undefined} info={formErrors.cultureFit ? formErrors.cultureFit.description : undefined} inline required>
        <RadioButton label='High risk' id='cultureFitHighRisk' value='cultureFitHighRisk' checked={formData.cultureFit === 'cultureFitHighRisk'}/>
        <RadioButton label='Signs of risk' id='cultureFitSomeRisk' value='cultureFitSomeRisk' checked={formData.cultureFit === 'cultureFitSomeRisk'}/>
        <RadioButton label='Indeterminate' id='cultureFitIndeterminate' value='cultureFitIndeterminate' checked={formData.cultureFit === 'cultureFitIndeterminate'}/>
        <RadioButton label='Good' id='cultureFitGood' value='cultureFitGood' checked={formData.cultureFit === 'cultureFitGood'}/>
        <RadioButton label='Perfect' id='cultureFitPerfect' value='cultureFitPerfect' checked={formData.cultureFit === 'cultureFitPerfect'}/>
      </RadioButtonGroup>

      <RadioButtonGroup {...stepFields[3][3]} onChange={(e) => {
            dispatch({
                type: 'setFieldValue',
                payload: {
                    ...stepFields[3][3],
                    value: e.target.value
                }
            });
        }} status={formErrors.finalRecommendation ? 'error' : undefined} info={formErrors.finalRecommendation ? formErrors.finalRecommendation.description : undefined} inline required>
        <RadioButton label='Do not recommend' id='doNotRecommend' value='doNotRecommend' checked={formData.finalRecommendation === 'doNotRecommend'}/>
        <RadioButton label='Indeterminate' id='noRecommendation' value='noRecommendation' checked={formData.finalRecommendation === 'noRecommendation'}/>
        <RadioButton label='Recommend' id='recommend' value='recommend' checked={formData.finalRecommendation === 'recommend'}/>
      </RadioButtonGroup>

      <TextArea {...stepFields[3][4]} value={formData.recommendationComments} onChange={(e) => {
            dispatch({
                type: 'setFieldValue',
                payload: { ...stepFields[3][4], value: e.target.value }
            });
        }}/>
    </Grid>);
};
export const MultiStepModal = (args) => {
    const { dismiss } = useModalContext();
    const { push: pushToaster } = useToaster();
    const [loading, setLoading] = useState(false);
    const [banners, setBanners] = useState();
    const bannerHandleRef = useRef(null);
    const [state, dispatch] = useReducer(reducer, initialState);
    const finalStep = state.currentStepIndex === state.numSteps - 1;
    const submitStep = () => {
        setLoading(true);
        setTimeout(() => {
            dispatch({ type: 'submitCurrentStep' });
            if (!finalStep)
                setLoading(false);
        }, loadingTimeoutMS);
    };
    useEffect(() => {
        if (banners && bannerHandleRef.current)
            bannerHandleRef.current.focus();
    }, [banners]);
    useEffect(() => {
        const bannerErrors = Object.keys(state.formErrors)
            .filter(errorField => {
            return stepFields[state.currentStepIndex].find(field => field.name === errorField);
        })
            .map(errorField => state.formErrors[errorField]);
        if (bannerErrors.length) {
            setBanners(<Banner messages={bannerErrors} variant='urgent' handle={bannerHandleRef}/>);
        }
        else {
            setBanners(undefined);
        }
    }, [state.currentStepIndex, state.formErrors]);
    const stepActions = useMemo(() => {
        return (<>
        <Button onClick={() => {
                dispatch({ type: 'cancel' });
                dismiss();
            }} disabled={loading}>
          Cancel
        </Button>
        <div>
          {state.currentStepIndex > 0 && (<Button onClick={() => dispatch({ type: 'setStep', payload: state.currentStepIndex - 1 })} disabled={loading}>
              Previous
            </Button>)}
          {!finalStep && (<Button variant='primary' onClick={submitStep} disabled={loading}>
              Next
            </Button>)}
          {finalStep && (<Button type='submit' variant='primary' onClick={(e) => {
                    e.preventDefault();
                    submitStep();
                }} disabled={loading}>
              Finish
            </Button>)}
        </div>
      </>);
    }, [state.currentStepIndex, loading]);
    const stepData = useMemo(() => {
        const steps = [
            {
                id: 'applicant_details',
                name: 'Applicant details - personal information',
                description: 'This applicant has passed initial screening and has been cleared to have an interview scheduled. ' +
                    'Please confirm their details and have a discussion regarding the open position and the company.',
                banners,
                content: (<ApplicantDetailsFields formData={state.formData} formErrors={state.formErrors} dispatch={dispatch}/>)
            },
            {
                id: 'interview_notes',
                name: 'Interview notes',
                banners,
                content: (<InterviewNotesFields formData={state.formData} formErrors={state.formErrors} dispatch={dispatch}/>)
            },
            {
                id: 'recommendations',
                name: 'Final recommendations',
                description: 'Based on your screening call with the applicant please submit your recomendations.',
                banners,
                content: (<RecommendationsFields formData={state.formData} formErrors={state.formErrors} dispatch={dispatch}/>)
            }
        ];
        if (state.numSteps === 4) {
            steps.splice(2, 0, {
                id: 'next_interview',
                name: 'Next interview',
                description: 'Please select an individual to conduct the next interview.',
                banners,
                content: (<NextInterviewFields formData={state.formData} formErrors={state.formErrors} dispatch={dispatch}/>)
            });
        }
        return steps;
    }, [state.formData, state.formErrors, state.currentStepIndex, banners, loading]);
    useEffect(() => {
        if (state.finished) {
            dismiss();
            pushToaster({
                id: 'CASE-12345',
                label: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.',
                href: '/?path=/story/work-caseview--case-view-demo',
                onClick: () => { }
            });
        }
    }, [state.finished]);
    return (<Modal heading={args.heading} progress={loading
            ? { message: `Submitting ${stepData[state.currentStepIndex].name.toLowerCase()}...` }
            : undefined} actions={stepActions} onRequestDismiss={() => !loading}>
      <MultiStepForm steps={stepData} currentStepId={stepData[state.currentStepIndex].id} stepIndicator={args.stepIndicator}/>
    </Modal>);
};
//# sourceMappingURL=MultiStepForm.mocks.jsx.map