import React, {
    FC, forwardRef, memo, useEffect, useRef, useState
} from 'react';
import lottie, { AnimationItem } from 'lottie-web';
import { cn }                    from '../../util/bem';
import './lottie.component.scss';

export type LottiePropsType = {
  className?: string;
  speed?: number;
  loop?: boolean;
  autoplay?: boolean;
  start?: boolean;
  playFrom?: number;
  src?: string;
  animationData?: { [key: string]: any };
}

const className = cn('lottie');

export const Lottie: FC<LottiePropsType> = memo(forwardRef((props, ref: React.Ref<HTMLDivElement>) => {
    const [ cardAnimation, setCardAnimation ] = useState<AnimationItem | null>(null);
    const animationRef = useRef<HTMLDivElement | null>(null);

    const loadLottie = async (container: HTMLDivElement) => {
        const animation = await lottie.loadAnimation({
            container,
            renderer:      'svg',
            loop:          props.loop,
            autoplay:      props.autoplay,
            animationData: props.animationData
        });
        animation.setSpeed(props.speed || 1);
        setCardAnimation(animation);
    };

    useEffect(() => {
        if (!!animationRef.current && !cardAnimation) {
            loadLottie(animationRef.current);
        }
    }, [ animationRef.current, cardAnimation ]);

    useEffect(() => {
        if (props.start) {
            // @ts-ignore
            cardAnimation?.goToAndPlay(props.playFrom || 0, true);
        } else {
            // @ts-ignore
            cardAnimation?.goToAndStop(props.playFrom || 0, true);
        }
    }, [ cardAnimation, props.start, props.playFrom ]);

    return (
        <div ref={ ref } className={ className('', null, props.className) }>
            <div ref={ animationRef } />
        </div>

    );
}));

Lottie.defaultProps = { autoplay: true, loop: true, speed: 1, start: true };

Lottie.displayName = 'Lottie';
