import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { COLORPICKER, DROPDOWN, INPUT, RADIO, TEXTAREA, TOGGLE } from '../../constants/schemaComponentTypes';
import { SMALL, MEDIUM, LARGE } from '../../constants/sizes';
import { newlineToBr, getLocalizionString } from '../../tools/stringTools';
import { CENTER, LEFT, RIGHT } from '../../constants/alignment';
import { useCarouselA11yVisible } from '../../tools/a11y/useCarouselA11yVisible';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/CarouselSlideImage.scss';
import { EMPHASIS, PRIMARY, SECONDARY } from '../../constants/components/schemas/button-types';
import Button from '../button/Button';

const n = createNamespace('CarouselSlideImage');

export const IMAGE_SLIDE_TYPE = 'IMAGE_ONLY';

const IMAGE_SIZING_FILL = 'fill';
const IMAGE_SIZING_FIT = 'fit';

const CarouselSlideImage = ({
    data: {
        title,
        text,
        image,
        titleColor,
        textColor,
        textSize,
        backgroundColor,
        imageSizing,
        slideLink,
        titleSize,
        textAlignment,
        overlayColor,
        isButtonVisible,
        buttonLabel,
        buttonType
    },
    i18n: {
        learnMore
    },
    settings,
    isPreviewMode,
    insideActiveRange
}) => {
    const containerRef = useRef();
    const [, tabIndex] = useCarouselA11yVisible(containerRef, insideActiveRange);
    const hasCallToAction = !!slideLink;
    const imageUrl = image ? image.url : '';
    const componentVariables = {
        'title-color': titleColor,
        'text-color': textColor,
        height: settings.height ? `${settings.height}px` : null,
        'mobile-height': settings.mobileHeight ? `${settings.mobileHeight}px` : null,
        'background-color': backgroundColor,
        'image-url': imageUrl && `url("${imageUrl}")`,
        'overlay-color': overlayColor
    };

    const containerProps = n(
        'content',
        [imageSizing, textSize && `text-size-${textSize}`]
    ).withTestId().withVariables(componentVariables);

    const shouldRenderContentText = title || text;

    const openInNewTabOnClick = e => {
        e.preventDefault();
        slideLink && window.open(getLocalizionString(slideLink), '_blank');
    };

    const openInNewTabOnKeyDown = e => {
        if (e.key === ' ' || e.key === 'Enter') {
            e.preventDefault();
            slideLink && window.open(getLocalizionString(slideLink), '_blank');
        }
    };

    const slideContent = shouldRenderContentText && (
        <div {...n('text', [textAlignment && `align-${textAlignment}`]).withTestId().props}>
            {title && (
                <div {...n('title', [titleSize && `text-size-${titleSize}`]).withTestId().props}>
                    {newlineToBr(getLocalizionString(title))}
                </div>
            )}
            {text && (
                <div {...n('description').withTestId().props}>
                    {newlineToBr(getLocalizionString(text))}
                </div>
            )}
            {isButtonVisible && (
                <div {...n('button').withTestId().withE2EId().props}>
                    <Button
                        type={buttonType}
                        onClick={openInNewTabOnClick}
                        tabIndex={tabIndex}
                        onKeyDown={openInNewTabOnKeyDown}
                    >
                        {buttonLabel ? getLocalizionString(buttonLabel) : learnMore}
                    </Button>
                </div>
            )}
        </div>
    );

    if (hasCallToAction && !isPreviewMode) {
        return (
            <div
                {...containerProps.props}
                onClick={openInNewTabOnClick}
                onKeyDown={openInNewTabOnKeyDown}
                ref={containerRef}
                tabIndex={tabIndex}
                aria-label={getLocalizionString(title)}
            >
                {slideContent}
            </div>
        );
    }
    return <div {...containerProps.props} ref={containerRef}>{slideContent}</div>;
};

const TEXT_SIZES_OPTIONS = [SMALL, MEDIUM, LARGE];
const TEXT_ALIGNMENT_OPTIONS = [LEFT, CENTER, RIGHT];

const IMAGE_SIZING_OPTIONS = [
    { value: IMAGE_SIZING_FILL, label: IMAGE_SIZING_FILL },
    { value: IMAGE_SIZING_FIT, label: IMAGE_SIZING_FIT }
];

const BUTTON_TYPES = [PRIMARY, SECONDARY, EMPHASIS];

CarouselSlideImage.schema = () => ({
    name: 'Carousel Slide Image',
    iconName: 'carousel',
    form: {
        title: {
            title: 'uieditor.sfbComponent.carouselSlideImage.title.title',
            type: INPUT,
            defaultValue: 'uieditor.sfbComponent.carouselSlideImage.title.defaultValue'
        },
        text: {
            title: 'uieditor.sfbComponent.carouselSlideImage.blurb.title',
            type: TEXTAREA,
            defaultValue: 'uieditor.sfbComponent.carouselSlideImage.blurb.defaultValue'
        },
        titleColor: {
            title: 'uieditor.sfbComponent.carouselSlideImage.titleColor.title',
            type: COLORPICKER
        },
        textColor: {
            title: 'uieditor.sfbComponent.carouselSlideImage.textColor.title',
            type: COLORPICKER
        },
        textSize: {
            title: 'uieditor.sfbComponent.carouselSlideImage.textSize.title',
            type: DROPDOWN,
            defaultValue: TEXT_SIZES_OPTIONS[0].value,
            options: TEXT_SIZES_OPTIONS
        },
        imageUrl: {
            title: 'uieditor.sfbComponent.carouselSlideImage.imageUrl.title',
            type: INPUT,
            defaultValue: ''
        },
        imageSizing: {
            title: 'uieditor.sfbComponent.carouselSlideImage.imageSizing.title',
            type: DROPDOWN,
            defaultValue: IMAGE_SIZING_OPTIONS[0].value,
            options: IMAGE_SIZING_OPTIONS
        },
        slideLink: {
            title: 'uieditor.sfbComponent.carouselSlideImage.url.title',
            defaultValue: '',
            type: INPUT
        },
        backgroundColor: {
            title: 'uieditor.sfbComponent.carouselSlideImage.backgroundColor.title',
            defaultValue: '#eee',
            type: COLORPICKER
        },
        titleSize: {
            title: 'uieditor.sfbComponent.carouselSlideImage.titleSize.title',
            type: DROPDOWN,
            defaultValue: LARGE.value,
            options: TEXT_SIZES_OPTIONS
        },
        textAlignment: {
            title: 'uieditor.sfbComponent.carouselSlideImage.textAlignment.title',
            type: DROPDOWN,
            defaultValue: CENTER.value,
            options: TEXT_ALIGNMENT_OPTIONS
        },
        overlayColor: {
            title: 'uieditor.sfbComponent.carouselSlideImage.overlayColor.title',
            type: COLORPICKER
        },
        isButtonVisible: {
            labelOn: 'uieditor.sfbComponent.carouselSlideImage.isButtonVisible.labelOn',
            labelOff: 'uieditor.sfbComponent.carouselSlideImage.isButtonVisible.labelOff',
            defaultValue: false,
            type: TOGGLE
        },
        buttonLabel: {
            title: 'uieditor.sfbComponent.carouselSlideImage.buttonLabel.title',
            type: INPUT,
            defaultValue: 'Learn More'
        },
        buttonType: {
            title: 'uieditor.sfbComponent.carouselSlideImage.buttonType.title',
            type: RADIO,
            defaultValue: BUTTON_TYPES[0].value,
            options: BUTTON_TYPES
        }
    }
});

CarouselSlideImage.propTypes = {
    settings: PropTypes.shape({
        height: PropTypes.number,
        mobileHeight: PropTypes.number
    }),
    data: PropTypes.shape({
        title: PropTypes.oneOfType([PropTypes.string, PropTypes.shape({
            value: PropTypes.string
        })]),
        text: PropTypes.oneOfType([PropTypes.string, PropTypes.shape({
            value: PropTypes.string
        })]),
        image: PropTypes.shape({
            url: PropTypes.string
        }),
        titleColor: PropTypes.string,
        textColor: PropTypes.string,
        textSize: PropTypes.oneOf(TEXT_SIZES_OPTIONS.map(({ value }) => value)),
        backgroundColor: PropTypes.string,
        imageSizing: PropTypes.oneOf(IMAGE_SIZING_OPTIONS.map(({ value }) => value)),
        slideLink: PropTypes.oneOfType([PropTypes.string, PropTypes.shape({
            value: PropTypes.string
        })]),
        titleSize: PropTypes.oneOf(TEXT_SIZES_OPTIONS.map(({ value }) => value)),
        textAlignment: PropTypes.oneOf(TEXT_ALIGNMENT_OPTIONS.map(({ value }) => value)),
        overlayColor: PropTypes.string,
        isButtonVisible: PropTypes.bool,
        buttonLabel: PropTypes.shape({
            value: PropTypes.string
        }),
        buttonType: PropTypes.oneOf(BUTTON_TYPES.map(({ value }) => value))
    }),
    i18n: PropTypes.shape({
        learnMore: PropTypes.string
    }),
    isPreviewMode: PropTypes.bool,
    insideActiveRange: PropTypes.bool
};

CarouselSlideImage.defaultProps = {
    settings: {
    },
    data: {
        title: null,
        text: null,
        image: {
            url: null
        },
        titleColor: null,
        textColor: null,
        textSize: null,
        backgroundColor: null,
        imageSizing: null,
        slideLink: null,
        titleSize: null,
        textAlignment: CENTER.value,
        overlayColor: null,
        isButtonVisible: false,
        buttonLabel: null,
        buttonType: PRIMARY.value
    },
    i18n: {
        learnMore: 'Learn More'
    },
    isPreviewMode: false,
    insideActiveRange: false
};

export default CarouselSlideImage;
