import * as lottie from 'lottie-web';
import { Component, ReactNode, RefObject } from 'react';
import * as React from 'react';
import animationService from '../../services/animationService';
import { IRewardCardProps } from './rewardCardProps';

export class AnimationRewardCard extends Component<IRewardCardProps, {}> {

    private lottieElem: RefObject<HTMLDivElement>;

    constructor(props: IRewardCardProps) {
        super(props);
        this.lottieElem = React.createRef();
    }

    public componentDidMount() {
        if (this.props.animation.jsonDescription) {
            this.playLottieAnimation();
        }
    }

    public render(): ReactNode {
        return (
            <div className='nonstop ns-reward-card-holder'>
                <div className='ns-container d-flex ns-h-100'>
                    <div className='nonstop-card text-center align-self-center justify-content-center ns-w-100 animated fadeIn'>
                        <div className='ns-row'>
                            <div className='ns-col-12'>
                                <div id='lottie' ref={this.lottieElem}></div>
                                <div className='ns-award-amination-text'>
                                    <p>Congratulations! You earned </p>
                                    <div className='ns-award-animation-icon'>
                                        <svg id='Layer_1' data-name='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'>
                                            <title>Logo Vector</title>
                                            <circle className='coin-icon-filled' cx='6.5' cy='6.5' r='6' />
                                            <path d='M14,12.79l.69-4.14L10.3,14.17h2.76l-.69,4.13,4.37-5.51Z' transform='translate(-7 -7)' />
                                        </svg>
                                    </div>
                                    <p><span className='text-highlight'> {this.props.reward.pointsAwardedDisplay} points</span> {this.props.reward.description}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    private playLottieAnimation() {
        const animationConfig = animationService.getAnimationConfiguration(this.props.animation.name, this.props.reward.pointsAwardedDisplay);
        if (!animationConfig) {
            this.props.onFinish();
        } else {
            if (this.props.onStart) {
                this.props.onStart();
            }
            lottie.setLocationHref(document.location.href);
            animationConfig.container = this.lottieElem.current;
            const lottieAnimation = lottie.loadAnimation(animationConfig);
            lottieAnimation.play();
            lottieAnimation.addEventListener('complete', () => {
                this.props.onFinish();
            });
        }
    }
}