import { useReducer, useMemo, useState, useEffect, useRef } from 'react';
import { Button, Banner, Flex, MultiStepForm, Text, useModalManager } from '@pega/cosmos-react-core';
import { loadingTimeoutMS } from '../Progress/Progress.mocks';
import { ApplicantDetailsFields, initialState, InterviewNotesFields, MultiStepModal, NextInterviewFields, RecommendationsFields, reducer, stepFields } from './MultiStepForm.mocks';
export default {
    title: 'Core/MultiStepForm',
    component: MultiStepForm,
    args: {
        heading: 'HR Screening',
        stepIndicator: 'horizontal'
    },
    argTypes: {
        heading: { control: { type: 'text' } },
        stepIndicator: { options: ['horizontal', 'vertical', 'none'], control: { type: 'select' } }
    }
};
export const MultiStepFormDemo = (args) => {
    const [loading, setLoading] = useState(false);
    const [banners, setBanners] = useState();
    const bannerHandleRef = useRef(null);
    const [state, dispatch] = useReducer(reducer, initialState);
    const submitStep = () => {
        setLoading(true);
        setTimeout(() => {
            dispatch({ type: 'submitCurrentStep' });
            setLoading(false);
        }, loadingTimeoutMS);
    };
    useEffect(() => {
        if (banners && bannerHandleRef.current)
            bannerHandleRef.current.focus();
    }, [banners]);
    useEffect(() => {
        const fieldIndex = state.numSteps === 3 && state.currentStepIndex === 2 ? 3 : state.currentStepIndex;
        const bannerErrors = Object.keys(state.formErrors)
            .filter(errorField => {
            return stepFields[fieldIndex].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, state.numSteps]);
    const stepData = useMemo(() => {
        const stepActions = (<>
        <Button onClick={() => {
                dispatch({ type: 'cancel' });
            }} disabled={loading}>
          Cancel
        </Button>
        <div>
          {state.currentStepIndex > 0 && (<Button onClick={() => dispatch({ type: 'setStep', payload: state.currentStepIndex - 1 })} disabled={loading}>
              Previous
            </Button>)}
          {state.currentStepIndex !== state.numSteps - 1 && (<Button variant='primary' onClick={submitStep} disabled={loading}>
              Next
            </Button>)}
          {state.currentStepIndex === state.numSteps - 1 && (<Button type='submit' variant='primary' onClick={(e) => {
                    e.preventDefault();
                    submitStep();
                }} disabled={loading}>
              Finish
            </Button>)}
        </div>
      </>);
        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}/>),
                actions: stepActions
            },
            {
                id: 'interview_notes',
                name: 'Interview notes',
                banners,
                content: (<InterviewNotesFields formData={state.formData} formErrors={state.formErrors} dispatch={dispatch}/>),
                actions: stepActions
            },
            {
                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}/>),
                actions: stepActions
            }
        ];
        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}/>),
                actions: stepActions
            });
        }
        return steps;
    }, [state.formData, state.formErrors, state.currentStepIndex, banners, loading]);
    return (<>
      {(state.cancelled || state.finished) && (<Flex container={{ gap: 2, alignItems: 'center' }}>
          <Text variant='h1'>HR screening {state.cancelled ? 'cancelled' : 'finished'}</Text>
          <Button onClick={() => {
                dispatch({ type: 'restart' });
            }}>
            Restart
          </Button>
        </Flex>)}

      {!state.cancelled && !state.finished && (<MultiStepForm heading={args.heading} steps={stepData} currentStepId={stepData[state.currentStepIndex].id} stepIndicator={args.stepIndicator} progress={loading
                ? `Submitting ${stepData[state.currentStepIndex].name.toLowerCase()}...`
                : undefined}/>)}
    </>);
};
export const MultiStepFormInModalDemo = (args) => {
    const { create } = useModalManager();
    useEffect(() => {
        create(MultiStepModal, { heading: args.heading, stepIndicator: args.stepIndicator });
    }, []);
    return (<Button onClick={() => {
            create(MultiStepModal, { heading: args.heading, stepIndicator: args.stepIndicator });
        }}>
      Open Modal
    </Button>);
};
//# sourceMappingURL=MultiStepForm.stories.jsx.map