/* eslint-disable jsx-a11y/label-has-associated-control */
import { ColorSchemeName, colorSchemeConfig } from '@preply/ds-core';
import React, { FC, useCallback } from 'react';

import { useTokenSearchContext } from '../providers/useTokenSearchContext';

import { Div, Select } from './SchemeSwitcher.styles';

type Props = {
    onChange?: (value: string) => void;
};

export const SchemeSwitcher: FC<Props> = ({ onChange }) => {
    const { colorScheme, setColorScheme } = useTokenSearchContext();

    const handleChange = useCallback(
        (ev: React.ChangeEvent<HTMLSelectElement>) => {
            const newColorScheme = ev.target.value as ColorSchemeName;
            window?.localStorage?.setItem('storybook.ds-color-scheme', newColorScheme);
            setColorScheme(newColorScheme ?? undefined);
            onChange?.(newColorScheme);
        },
        [onChange, setColorScheme],
    );

    return (
        <Div isNotDefault={!!colorScheme}>
            <label>Color Scheme</label>
            <Select value={colorScheme} onChange={handleChange}>
                <option key="none" value="">
                    -- no color scheme --
                </option>
                {Object.keys(colorSchemeConfig).map(key => (
                    <option key={key} value={key}>
                        {key}
                    </option>
                ))}
            </Select>
        </Div>
    );
};
