2025-03-12 16:58:15 +03:00

82 lines
2.4 KiB
TypeScript

'use client';
import { createContext, type PropsWithChildren, useMemo, useReducer, useState } from 'react';
type Action = { payload: Steps; type: 'SET_STEP' } | { type: 'NEXT_STEP' } | { type: 'PREV_STEP' };
type ContextType = {
customerId: null | string;
nextStep: () => void;
prevStep: () => void;
setCustomerId: (customerId: string) => void;
setStep: (step: Steps) => void;
step: Steps;
};
type State = { step: Steps };
type Steps = 'customer-select' | 'datetime-select' | 'service-select' | 'success';
const stepsSequence: Steps[] = ['customer-select', 'service-select', 'datetime-select', 'success'];
function stepsReducer(state: State, action: Action): State {
switch (action.type) {
case 'NEXT_STEP': {
const currentIndex = stepsSequence.indexOf(state.step);
const nextIndex = currentIndex + 1;
const nextStep = stepsSequence[nextIndex];
return nextStep ? { ...state, step: nextStep } : state;
}
case 'PREV_STEP': {
const currentIndex = stepsSequence.indexOf(state.step);
const previousIndex = currentIndex - 1;
const previousStep = stepsSequence[previousIndex];
return previousStep ? { ...state, step: previousStep } : state;
}
case 'SET_STEP': {
return { ...state, step: action.payload };
}
default:
return state;
}
}
function useCustomerState() {
const [customerId, setCustomerId] = useState<null | string>(null);
return { customerId, setCustomerId };
}
function useStep() {
const [state, dispatch] = useReducer(stepsReducer, { step: 'customer-select' });
const setStep = (payload: Steps) => dispatch({ payload, type: 'SET_STEP' });
const nextStep = () => dispatch({ type: 'NEXT_STEP' });
const previousStep = () => dispatch({ type: 'PREV_STEP' });
return { nextStep, prevStep: previousStep, setStep, ...state };
}
export const OrderContext = createContext<ContextType>({} as ContextType);
export function OrderContextProvider({ children }: Readonly<PropsWithChildren>) {
const { customerId, setCustomerId } = useCustomerState();
const { nextStep, prevStep, setStep, step } = useStep();
const value = useMemo(
() => ({
customerId,
nextStep,
prevStep,
setCustomerId,
setStep,
step,
}),
[customerId, nextStep, prevStep, setCustomerId, setStep, step],
);
return <OrderContext.Provider value={value}>{children}</OrderContext.Provider>;
}