import { ThemeMode } from '@/common/cache';
import { MovableModal } from '@/components';
import { isDarkTheme } from '@/layouts/RootLayout';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { Alert, message } from 'antd';
import { useCallback, useEffect, useRef, useState } from 'react';
import { Content, JSONEditor, Mode } from 'vanilla-jsoneditor';
import 'vanilla-jsoneditor/themes/jse-theme-dark.css';

export type JsonEditorModalProps = {
    title: string;
    data: string;
    tooltip?: string;
    onFinish: (json: string) => Promise<boolean>;
    onClose?: () => void;
}

const JsonEditorModal: React.FC<JsonEditorModalProps> = ({ title, data, tooltip, onFinish, onClose }) => {
    const [open, setOpen] = useState(true);
    const handleClose = useCallback(() => { setOpen(false); setTimeout(() => onClose?.(), 300); }, []);

    const editError = useRef(false);
    const configRef = useRef(JSON.parse(data));
    const editorRef = useRef(null);

    const [messageApi, contextHolder] = message.useMessage();

    useEffect(() => {
        if (!editorRef.current) {
            return;
        }
        let content: Content = {
            text: undefined,
            json: configRef.current,
        }
        new JSONEditor({
            target: editorRef.current,
            props: {
                content,
                mode: Mode.text,
                mainMenuBar: false,
                indentation: 4,
                onChange: (updatedContent, previousContent, { contentErrors }) => {
                    editError.current = !!contentErrors;
                    configRef.current = updatedContent;
                }
            }
        });
    }, []);

    const wrapperClassName = useEmotionCss(({ token }) => {
        const radius = token.borderRadius;
        return {
            width: '100%',
            height: 600,
            '.jse-text-mode': {
                borderTopLeftRadius: radius,
                borderTopRightRadius: radius,
                '.jse-contents': {
                    borderTopLeftRadius: radius,
                    borderTopRightRadius: radius,
                },
                '.jse-status-bar': {
                    borderBottomLeftRadius: radius,
                    borderBottomRightRadius: radius,
                },
            }
        };
    });

    const handleOk = useCallback(async () => {
        if (editError.current) {
            messageApi.error("语法错误");
            return;
        }
        const success = await onFinish(configRef.current.text);
        if (!success) {
            return;
        }
        handleClose();
    }, []);

    const tm = ThemeMode.get();
    const isDark = tm?.themeMode === 'dark' || (tm?.themeMode === 'auto' && isDarkTheme.matches);

    return (
        <MovableModal
            title={title}
            width={960}
            open={open}
            centered={true}
            maskClosable={false}
            onCancel={handleClose}
            onOk={handleOk}
        >
            {contextHolder}
            {tooltip && <Alert type="warning" showIcon={true} message={tooltip} style={{ marginBottom: 8 }} closable />}
            <div
                ref={editorRef}
                className={`${isDark ? 'jse-theme-dark' : ''} ${wrapperClassName}`}
            />
        </MovableModal >
    );
}

export default JsonEditorModal;
