import React, { useState } from 'react';
import PropTypes from 'prop-types';
import Cookies from 'js-cookie';
import { createNamespace } from '../../tools/namingTools';
import { localeShape } from '../../constants/prop-types/config';
import { LIGHT } from '../../constants/themeColor';
import Select from '../select/Select';
import { getStorefrontUrl, navigateTo } from '../../tools/urlTools';
// 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 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) {
            Cookies.set('locale-language', locale, { secure: true, SameSite: 'None' });
            setCurrentLanguage(locale);

            // Get the URL without locale query parameter
            const url = getStorefrontUrl(locale);
            const urlObj = new URL(url, window.location.origin);

            // Remove locale query parameter if it exists
            urlObj.searchParams.delete('locale');

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

    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;
