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

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

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

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


    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={props.structure.title ?? ""}
                onChange={(evn) => {

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


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

            />

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


