import React, { useEffect, useState } from 'react';
import Select, { components, SingleValueProps, OptionProps } from 'react-select';
import { useTranslation } from 'react-i18next';

type LanguageOption = { label: string; value: string };

const LANGS: LanguageOption[] = [
    { value: 'id', label: '🇮🇩 ID' },
    { value: 'en-GB', label: '🇬🇧 EN-UK' },
];

const getLanguageOption = (language?: string) =>
    LANGS.find((option) => option.value === language) || LANGS[0];

const Option = (props: OptionProps<LanguageOption, false>) => (
    <components.Option {...props}>
        <span className='flex items-center gap-1'>{props.data.label}</span>
    </components.Option>
);

const SingleVal = (props: SingleValueProps<LanguageOption, false>) => (
    <components.SingleValue {...props}>
        <span className='flex items-center gap-1'>{props.data.label}</span>
    </components.SingleValue>
);

const LanguageSwitcher: React.FC = () => {
    const { i18n } = useTranslation('common');
    const [mounted, setMounted]   = useState(false);
    const [selected, setSelected] = useState<LanguageOption>(LANGS[0]);

    useEffect(() => {
        setMounted(true);

        const savedLanguage = typeof window !== 'undefined' ? window.localStorage.getItem('app_lang_') : null;
        const selectedLanguage = getLanguageOption(savedLanguage || i18n.resolvedLanguage || i18n.language);
        setSelected(selectedLanguage);

        if (selectedLanguage.value !== i18n.language) {
            i18n.changeLanguage(selectedLanguage.value);
        }

        const handleLanguageChanged = (language: string) => {
            setSelected(getLanguageOption(language));
        };

        i18n.on('languageChanged', handleLanguageChanged);
        return () => {
            i18n.off('languageChanged', handleLanguageChanged);
        };
    }, [i18n]);

    const handleChange = async (opt: LanguageOption | null) => {
        if (!opt) return;
        setSelected(opt);
        window.localStorage.setItem('app_lang_', opt.value);
        await i18n.changeLanguage(opt.value);
    };

    if (!mounted) return null;

    return (
        <div style={{ width: 118 }}>
            <Select
                value={selected}
                options={LANGS}
                onChange={handleChange}
                isSearchable={false}
                menuPlacement='top'
                components={{
                    Option,
                    SingleValue: SingleVal,
                    IndicatorSeparator: () => null,
                }}
                styles={{
                    control: (base) => ({
                        ...base,
                        minHeight: 28,
                        height: 28,
                        paddingTop: 0,
                        paddingBottom: 0,
                        borderColor: '#d1d5db',
                        cursor: 'pointer',
                    }),
                    valueContainer: (base) => ({
                        ...base,
                        paddingTop: 0,
                        paddingBottom: 0,
                        paddingLeft: 6,
                    }),
                    indicatorsContainer: (base) => ({
                        ...base,
                        height: 24,
                    }),
                    dropdownIndicator: (base) => ({
                        ...base,
                        padding: 2,
                    }),
                    option: (base, state) => ({
                        ...base,
                        paddingTop: 4,
                        paddingBottom: 4,
                        height: 28,
                        fontSize: '0.875rem',
                        backgroundColor: state.isFocused ? '#f3f4f6' : 'white',
                        color: '#111827',
                    }),
                    menu: (base) => ({
                        ...base,
                        zIndex: 9999,
                    }),
                }}
            />
        </div>
    );
};

export default LanguageSwitcher;
