import {useState, useCallback, useEffect, useRef} from 'react'; import {Variant, Size} from 'types/VariantTypes'; export interface Props { selectedSize?: Size; selectedVariant: Variant; customizable?: boolean; readyText?: string; successText?: string; onAddToBag: (size?: Size) => Promise; classNameSuccess?: string; startDisabled?: boolean; } type Status = | 'READY' | 'PENDING' | 'ERROR' | 'SUCCESS' | 'NO_SIZE_SELECTED' | 'SIZE_SOLD_OUT'; const TEMP_STATUS_TIME = 3000; const useAddToBag = ({ selectedSize, selectedVariant, customizable, readyText = 'ADD TO BAG', successText = 'SUCCESSFULLY ADDED TO BAG', onAddToBag }: Props) => { const [status, setStatus] = useState('READY'); const timeout = useRef(); let text = readyText; let disabled = false; let loading = false; if (selectedVariant.coming_soon) { text = 'THIS ITEM IS COMING SOON'; disabled = true; } else if (!selectedVariant.can_sell) { text = 'THIS ITEM IS SOLD OUT'; disabled = true; } else if ( (selectedSize && !selectedSize.can_sell) || status === 'SIZE_SOLD_OUT' ) { text = 'SIZE SOLD OUT'; disabled = true; } else if (customizable) { text = 'PERSONALIZE'; } else if (status === 'NO_SIZE_SELECTED') { text = 'PLEASE SELECT A SIZE'; disabled = true; } else if (status === 'PENDING') { loading = true; disabled = true; } else if (status === 'ERROR') { text = 'UNABLE TO ADD ITEM TO BAG'; disabled = true; } else if (status === 'SUCCESS') { text = successText; disabled = true; } useEffect(() => { return () => { if (timeout.current) { clearTimeout(timeout.current); } }; }, [timeout]); useEffect(() => { if (selectedSize && status === 'NO_SIZE_SELECTED') { setStatus('READY'); if (timeout.current) clearTimeout(timeout.current); } }, [selectedSize, status, timeout]); const handleClick = useCallback( async (size?: Size) => { if (customizable) { window.location.href = selectedVariant.href; } else if (!selectedSize && !size) { setStatus('NO_SIZE_SELECTED'); timeout.current = setTimeout( () => setStatus('READY'), TEMP_STATUS_TIME ); } else if (size && !size.can_sell) { setStatus('SIZE_SOLD_OUT'); timeout.current = setTimeout( () => setStatus('READY'), TEMP_STATUS_TIME ); } else if (status === 'READY' && !disabled) { setStatus('PENDING'); try { await onAddToBag(size); setStatus('SUCCESS'); } catch (error) { setStatus('ERROR'); } finally { timeout.current = setTimeout( () => setStatus('READY'), TEMP_STATUS_TIME ); } } }, [ customizable, selectedSize, status, disabled, selectedVariant.href, onAddToBag ] ); return { text, loading, disabled, handleClick, status }; }; export default useAddToBag;