import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../../../tools/namingTools';
import { screenshotShape } from '../../../../constants/components/prop-types/product-image-viewer';
import Icon from '../../../../atoms/icon/Icon';
import Image from '../../../../atoms/image/Image';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/ProductImageViewerThumbnail.scss';

const n = createNamespace('ProductImageViewerThumbnail');

const ProductImageViewerThumbnail = ({ name, imageAlt, imageUrl, imageUrlSrcset,
    isVideo, navigateToSlide, slideIndex }) => {
    const hasImage = imageUrl || imageUrlSrcset;
    const ref = useRef();
    let tabIndex;

    if (ref.current?.parentElement?.parentElement?.classList?.contains('slick-active')) {
        tabIndex = 0;
    }

    const onKeyDownHandler = e => {
        if (e.key === ' ' || e.key === 'Enter') {
            e.preventDefault();
            navigateToSlide && navigateToSlide(slideIndex);
        }
    };

    return (
        <div
            ref={ref}
            {...n('wrapper', hasImage && 'with-image').withE2EId().props}
            tabIndex={tabIndex}
            onKeyDown={onKeyDownHandler}
        >
            {isVideo && (
                <>
                    <span {...n('text').props}>{name}</span>
                    <Icon {...n('icon').props} type="play" />
                </>
            )}
            {hasImage && (
                <Image
                    {...n('image', isVideo && 'video-preview').withTestId().withE2EId().props}
                    alt={imageAlt || name}
                    src={imageUrl}
                    srcSet={imageUrlSrcset}
                />
            )}
        </div>
    );
};

ProductImageViewerThumbnail.propTypes = {
    ...screenshotShape,
    ...{
        isVideo: PropTypes.bool
    }
};

ProductImageViewerThumbnail.defaultProps = {
    name: '',
    imageUrl: null,
    imageUrlSrcset: null,
    imageAlt: null,
    isVideo: false
};

export default ProductImageViewerThumbnail;
