import React, { useId, useState } from 'react';
import PropTypes from 'prop-types';
import Cookies from 'js-cookie';
import { Select, Button, SelectValue, Popover, ListBox, ListBoxItem } from 'react-aria-components';
import { createNamespace } from '../../tools/namingTools';
import { localeShape } from '../../constants/prop-types/config';
import { getStorefrontUrl, navigateTo } from '../../tools/urlTools';
import useUpwardPopoverPortalRoot from './useUpwardPopoverPortalRoot';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/LanguageSwitcher.scss';

const n = createNamespace('LanguageSwitcher');

const thai = 'th-TH';
const updateThaiLabel = langList => langList.map(langObj => {
    if (langObj.value === thai) {
        return {
            label: 'ไทย (ประเทศไทย)',
            value: thai
        };
    }
    return langObj;
});

const POPOVER_OFFSET = 8;
const POPOVER_CONTAINER_PADDING = 12;

const LanguageSwitcher = ({
    className: extraClass,
    code,
    available,
    i18n,
    placement = 'bottom',
    shouldFlip = true
}) => {
    const [currentLanguage, setCurrentLanguage] = useState(code);
    // Keep the legacy visible-control association stable for tenant CSS and
    // automation that still address languageSwitcher_label/select. React 18's
    // useId keeps this deterministic across SSR hydration as well.
    const uid = useId();
    const usesUpwardPortal = placement.startsWith('top');
    const upwardPortalRoot = useUpwardPopoverPortalRoot(usesUpwardPortal);

    if (!available || !available.length) {
        return null;
    }

    const updatedOptionsList = updateThaiLabel(available);

    const i18nWithDefaults = { ...LanguageSwitcher.defaultProps.i18n, ...i18n };
    const { languages: languageSelectLabel } = i18nWithDefaults;
    const buttonId = `languageSwitcher-select-${uid.replace(/:/g, '')}`;

    const onLanguageSwitch = locale => {
        if (locale) {
            Cookies.set('locale-language', locale, { secure: true, SameSite: 'None' });
            setCurrentLanguage(locale);

            const url = getStorefrontUrl(locale);
            const urlObj = new URL(url, window.location.origin);

            urlObj.searchParams.delete('locale');

            navigateTo(urlObj.toString());
        }
    };

    return (
        <Select
            {...n('wrapper').withClass(extraClass).withTestId().props}
            aria-label={languageSelectLabel}
            value={currentLanguage || null}
            onChange={onLanguageSwitch}
        >
            {/*
             * Retain the pre-React-Aria public selector names as aliases.
             * Storefront themes can contain custom CSS targeting these BEM
             * classes, so removing them would silently break those themes.
             */}
            <label
                {...n('label', 'hidden')
                    .withClass(['formLabel_label', 'select_label'])
                    .withTestId('label').props}
                htmlFor={buttonId}
            >
                <span className="formLabel_text select_text select_text--hidden">
                    {languageSelectLabel}
                </span>
            </label>
            <div className="select__container">
                <Button
                    {...n('button')
                        .withClass(['languageSwitcher_select', 'select__control'])
                        .withTestId().props}
                    id={buttonId}
                >
                    <span className="select__value-container select__value-container--has-value">
                        <SelectValue {...n('value').withClass('select__single-value').props} />
                    </span>
                </Button>
            </div>
            <Popover
                {...n('popover').withTestId().props}
                isNonModal
                placement={placement}
                shouldFlip={shouldFlip}
                offset={POPOVER_OFFSET}
                containerPadding={POPOVER_CONTAINER_PADDING}
                {...(upwardPortalRoot
                    ? { UNSTABLE_portalContainer: upwardPortalRoot }
                    : {})}
            >
                <ListBox {...n('listbox').withTestId().props}>
                    {updatedOptionsList.map(({ value, label }) => (
                        <ListBoxItem
                            key={value}
                            id={value}
                            {...n('option').withTestId().props}
                        >
                            {label}
                        </ListBoxItem>
                    ))}
                </ListBox>
            </Popover>
        </Select>
    );
};

LanguageSwitcher.propTypes = {
    ...localeShape,
    ...{
        i18n: PropTypes.shape({
            languages: PropTypes.string
        }),
        placement: PropTypes.string,
        shouldFlip: PropTypes.bool
    }
};

LanguageSwitcher.defaultProps = {
    code: null,
    available: null,
    i18n: {
        languages: 'Choose a language'
    }
};

export default LanguageSwitcher;
