import {
    useEffect,
    useState,
} from 'react';

import { useAppConfig } from '@/stores/appConfig';
import CodeEditor from '@uiw/react-textarea-code-editor';

import { useLang } from '@/lang/Lang';
import { useLLText } from '@/lang/localizationService';

import DataDescription from './components/DataDescription';
import DataLabel from './components/DataLabel';
import { ItemDataProps } from './types';

export const CodeData = (props: ItemDataProps) => {

    const lang = useLang();
    const titlePlaceholder = useLLText(props.structure.title ?? '', lang);

    const { isDarkTheme } = useAppConfig();

    const [localValue, setLocalValue] = useState(props.getValue());

    useEffect(() => {
        props.setValue(localValue);
    }, [localValue]);

    useEffect(() => {

        if (localValue === undefined || localValue === null) {
            setLocalValue(false);
        }


    }, []);




    const getValue = () => {
        return !!localValue ? localValue : "";
    };

    const getCodeLanguage = () => {
        switch (props.structure?.codeLang) {
            case 'js':
                return 'js';
            case 'css':
                return 'css';
            default:
                return 'text/plain';
                break;
        }
    };


    return (
        <>

            <DataLabel {...props} />

            <CodeEditor
                value={getValue()}
                data-color-mode={isDarkTheme ? 'dark' : 'light'}

                language={getCodeLanguage()}
                placeholder={titlePlaceholder}
                onChange={(evn) => {

                    if (props.onlyShow || !props.structure.editable) {
                        return;
                    }


                    setLocalValue(evn.target.value);
                }}
                padding={15}

            />

            <DataDescription {...props} />
        </>
    );
};


