import React from 'react';
import PropTypes from 'prop-types';
import Button from '../../button/Button';
import Icon from '../../icon/Icon';
import Image from '../../image/Image';
import SearchBarV2 from '../../search-bar-v2/SearchBarV2';
import { createNamespace } from '../../../tools/namingTools';
import { getListingUrl, navigateTo } from '../../../tools/urlTools';
import { useResponsive } from '../../../tools/widths/useResponsive';
import { IMAGE_STYLE_HEIGHTS, IMAGE_STYLE_HEIGHTS_MOBILE, SEARCH_BAR_HEIGHTS_VALUES,
    SEARCH_BAR_WIDTH } from '../../../constants/atoms/hero-banner-styles';
import { SCALE_TO_FIT_SCREEN } from '../../../constants/components/hero-banner';
import { MEDIUM, SMALL } from '../../../constants/sizes';
import { SIZE_DEFAULT } from '../../../constants/buttons';
import { PRIMARY, LINK } from '../../../constants/components/schemas/button-types';
import { imageStylePropTypes } from '../../../constants/components/prop-types/hero-banner';
import { headerDataStore as dataStore } from '../../../store/header';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/ImageStyle.scss';
import { getLocalizionString, getImageUploaderAltText } from '../../../tools/stringTools';

const n = createNamespace('ImageStyle');

const HeroStyle = ({
    settings,
    i18n,
    locale
}) => {
    const { mediumDown: isMobile } = useResponsive();
    const sizesToUse = isMobile ? IMAGE_STYLE_HEIGHTS_MOBILE : IMAGE_STYLE_HEIGHTS;

    const {
        height,
        isTaglineVisible,
        isTitleVisible,
        isTextVisible,
        isButton1Visible,
        isButtonVisible: legacyIsButtonVisible,
        isButton2Visible,
        isSearchBarVisible,
        tagline,
        title,
        text,
        button1Label,
        buttonLabel: legacyButtonLabel,
        button2Label,
        backgroundImage,
        imageSize,
        taglineColor,
        titleColor,
        descriptionColor,
        overlayColor,
        backgroundColor,
        shadowColor,
        textAlignment,
        textSize,
        button1Type,
        buttonType: legacyButtonType,
        button1Link,
        buttonLink: legacyButtonLink,
        button2Type,
        button2Link,
        searchCornerRadius,
        searchPlaceholder,
        searchPlaceholderTextColor,
        searchIcon,
        searchBorderColor,
        searchBackgroundColor,
        searchButtonColor,
        searchIconColor,
        // ImageStyle specific knobs
        foregroundImage,
        foregroundImagePosition,
        foregroundImageSize,
        textPositionImageStyle,
        searchBarWidthImageStyle
    } = settings;

    const { searchValue, setSearchValue } = dataStore();

    const onSearch = (formData, e) => {
        e.preventDefault();
        setSearchValue(formData.inputSearch);
        navigateTo(getListingUrl(locale, formData.inputSearch));
    };

    const searchBarSettings = {
        searchValue,
        inputName: 'inputSearch',
        onSearch,
        height: SEARCH_BAR_HEIGHTS_VALUES[MEDIUM.value],
        hiddenLabel: true,
        label: i18n?.search,
        searchBackgroundColor,
        searchBorderColor,
        searchCornerRadius,
        searchBorderVisible: true,
        submitIconOnly: true,
        searchIcon,
        searchIconColor,
        searchButtonColor,
        searchPlaceholder: searchPlaceholder || i18n?.search,
        searchPlaceholderTextColor,
        searchBarMinWidth: SEARCH_BAR_WIDTH.min,
        searchBarMaxWidth: searchBarWidthImageStyle,
        hasBoxShadow: false
    };

    const hasBackgroundImage = Boolean(backgroundImage?.url);

    const primaryButtonVisible = isButton1Visible ?? legacyIsButtonVisible ?? true;
    const secondaryButtonVisible = isButton2Visible ?? false;
    const shouldRenderButtons = primaryButtonVisible || secondaryButtonVisible;
    const primaryButtonLabel = button1Label ?? legacyButtonLabel;
    const secondaryButtonLabel = button2Label;
    const primaryButtonType = button1Type ?? legacyButtonType ?? PRIMARY.value;
    const secondaryButtonType = button2Type ?? PRIMARY.value;
    const primaryButtonLink = button1Link ?? legacyButtonLink;
    const secondaryButtonLink = button2Link;
    const secondaryButtonText = secondaryButtonLabel
        || (primaryButtonVisible && primaryButtonLabel)
        || i18n?.learnMore;

    // on mobile, always screen-width
    const backgroundImageModifiers = [
        imageSize && (isMobile ? SCALE_TO_FIT_SCREEN.value : imageSize)
    ];

    const imageUrl = foregroundImage?.url;

    // Alt-text with localization support - uses IMAGE_UPLOADER's native alt field
    // Supports both legacy (plain string) and new (localized object) formats
    const imageAlt = getImageUploaderAltText(foregroundImage)
                  || getLocalizionString(title)
                  || '';

    // Alt-text with localization support for background image
    const backgroundImageAltText = getImageUploaderAltText(backgroundImage)
                                || getLocalizionString(title)
                                || '';

    const componentVariables = {
        'tagline-color': taglineColor,
        'title-color': titleColor,
        'description-color': descriptionColor,
        'background-color': backgroundColor,
        'image-url': hasBackgroundImage && `url("${backgroundImage?.url}")`,
        'overlay-color': overlayColor,
        'shadow-color': shadowColor,
        height: `${sizesToUse[height]}px`
    };

    const handlePrimaryButtonClick = () => primaryButtonLink && navigateTo(primaryButtonLink);
    const handleSecondaryButtonClick = () => secondaryButtonLink && navigateTo(secondaryButtonLink);

    const buttonSize = textSize === SMALL.value ? SMALL.value : SIZE_DEFAULT;

    // <img> element should be high priority to improve LCP
    const imageAttributes = {
        fetchpriority: 'high'
    };

    const foregroundImageModifiers = [
        foregroundImageSize && `image-${foregroundImageSize}`,
        foregroundImagePosition && `image-align-${foregroundImagePosition}`,
        !imageUrl && 'default-image'
    ];

    const wrapperModifiers = [
        height && `height-${height}`
    ];

    const contentModifiers = [
        foregroundImagePosition && `image-align-${foregroundImagePosition}`
    ];

    const detailsModifiers = [
        height && `height-${height}`,
        textAlignment && `align-${textAlignment}`,
        textPositionImageStyle && `position-${textPositionImageStyle}`,
        foregroundImagePosition && `image-align-${foregroundImagePosition}`
    ];

    const textModifiers = [
        textSize && `text-size-${textSize}`
    ];

    return (
        <div {...n('wrapper', wrapperModifiers).withTestId().withE2EId().withVariables(componentVariables).props}>
            {
                backgroundImage?.url && (
                    <>
                        <Image
                            {...imageAttributes}
                            {...n('backgroundImage', backgroundImageModifiers).props}
                            src={backgroundImage?.url}
                            alt={backgroundImageAltText}
                        />
                        <div {...n('backgroundImageOverlay', backgroundImageModifiers).withTestId().props} />
                    </>

                )
            }
            <div {...n('content', contentModifiers).withTestId().withE2EId().props}>
                <div {...n('details', detailsModifiers).withTestId().withE2EId().props}>
                    {
                        isTaglineVisible && (
                            <div {...n('tagline', textModifiers).withTestId().withE2EId().props}>
                                {tagline}
                            </div>
                        )
                    }
                    {
                        isTitleVisible && (
                            <div {...n('title', textModifiers).withTestId().withE2EId().props}>
                                {title}
                            </div>
                        )
                    }
                    {
                        isTextVisible && (
                            <div {...n('text', textModifiers).withTestId().withE2EId().props}>
                                {text}
                            </div>
                        )
                    }
                    {shouldRenderButtons && (
                        <div {...n('buttonContainer').props}>
                            {primaryButtonVisible && (
                                <div {...n('button').withTestId().withE2EId().props}>
                                    <Button
                                        size={buttonSize}
                                        type={primaryButtonType !== LINK.value ? primaryButtonType : PRIMARY.value}
                                        buttonType={primaryButtonType !== LINK.value ? 'button' : LINK.value}
                                        onClick={handlePrimaryButtonClick}
                                        tabIndex={0}
                                    >
                                        {primaryButtonLabel || i18n?.learnMore}
                                        { primaryButtonType === LINK.value && <Icon type="caretRight" {...n('iconLink').props} /> }
                                    </Button>
                                </div>
                            )}
                            {secondaryButtonVisible && (
                                <div {...n('button').withTestId().withE2EId().props}>
                                    <Button
                                        size={buttonSize}
                                        type={secondaryButtonType !== LINK.value ? secondaryButtonType : PRIMARY.value}
                                        buttonType={secondaryButtonType !== LINK.value ? 'button' : LINK.value}
                                        onClick={handleSecondaryButtonClick}
                                        tabIndex={0}
                                    >
                                        {secondaryButtonText}
                                        { secondaryButtonType === LINK.value && <Icon type="caretRight" {...n('iconLink').props} /> }
                                    </Button>
                                </div>
                            )}
                        </div>
                    )}
                    {
                        shouldRenderButtons && isSearchBarVisible
                        && <div {...n('divider').props} />
                    }
                    {
                        isSearchBarVisible && (
                            <SearchBarV2 {...searchBarSettings} />
                        )
                    }
                </div>
                <div {...n('foregroundImage', foregroundImageModifiers).withTestId().withE2EId().props}>
                    {
                        imageUrl ? (
                            <Image src={imageUrl} alt={imageAlt} {...imageAttributes} />
                        ) : (
                            <Icon {...n('defaultImage').withTestId().props} type="image" width="64px" />
                        )
                    }
                </div>
            </div>
        </div>
    );
};

HeroStyle.propTypes = {
    i18n: PropTypes.object,
    locale: PropTypes.string,
    settings: PropTypes.shape(imageStylePropTypes)
};

HeroStyle.defaultProps = {
    i18n: {
        learnMore: 'Learn more',
        search: 'Search'
    },
    locale: 'en-US',
    settings: {}
};

export default HeroStyle;
