import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { localeShape } from '../../constants/prop-types/config';
import { LIGHT } from '../../constants/themeColor';
import Select from '../select/Select';
import './styles/LanguageSwitcher.scss';
import { getStorefrontUrl, navigateTo } from '../../tools/urlTools';

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 LanguageSwitcher = ({
    className: extraClass,
    code,
    available,
    i18n,
    pageId
}) => {
    const [currentLanguage, setCurrentLanguage] = useState(code);

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

    const updatedOptionsList = updateThaiLabel(available);

    const i18nWithDefaults = { ...LanguageSwitcher.defaultProps.i18n, ...i18n };
    const { languages: languageSelectLabel } = i18nWithDefaults;

    const onLanguageSwitch = ({ value: locale }) => {
        if (locale) {
            setCurrentLanguage(locale);
            navigateTo(getStorefrontUrl(locale));
        }
    };

    return (
        <div {...n('wrapper').withClass(extraClass).withTestId().props}>
            <Select
                label={languageSelectLabel}
                withBackground={false}
                theme={LIGHT.value}
                value={currentLanguage}
                size="auto"
                hiddenLabel
                options={updatedOptionsList}
                onChange={onLanguageSwitch}
                pageId={pageId}
            />
        </div>
    );
};

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

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

export default LanguageSwitcher;
