import { MDXEditor, type MDXEditorMethods, type MDXEditorProps } from '@mdxeditor/editor';
import type { CSSProperties, Ref } from 'react';
import { Label } from './Label';

type MDXEditorFieldProps = {
    label?: string;
    markdown: string;
    readOnly?: boolean;
    disabled?: boolean;
    onChange?: (markdown: string) => void;
    editorRef?: Ref<MDXEditorMethods | null>;
    themeClassName: string;
    plugins: MDXEditorProps['plugins'];
    contentEditableClassName?: string;
    className?: string;
    editorWrapperClassName?: string;
    editorWrapperStyle?: CSSProperties;
    editorClassName?: string;
    error?: string;
};

export function MDXEditorField({
    label,
    markdown,
    readOnly = false,
    disabled = false,
    onChange,
    editorRef,
    themeClassName,
    plugins,
    contentEditableClassName = 'mdx-content',
    className = '',
    editorWrapperClassName = 'post-mdx-editor mt-2 overflow-hidden rounded-xl border',
    editorWrapperStyle,
    editorClassName = '',
    error,
}: Readonly<MDXEditorFieldProps>) {
    const resolvedEditorClassName = `${themeClassName} ${editorClassName}`.trim();
    const editorModeKey = disabled || readOnly ? 'read-only' : 'editable';
    const resolvedEditorWrapperClassName =
        `${editorWrapperClassName} ${disabled ? 'post-mdx-editor--disabled' : 'post-mdx-editor--enabled'}`.trim();
    const resolvedEditorWrapperStyle: CSSProperties = {
        backgroundColor: disabled ? 'var(--field-disabled-bg)' : 'var(--field-bg)',
        borderColor: disabled ? 'var(--field-disabled-border)' : 'var(--field-border)',
        ...editorWrapperStyle,
    };

    return (
        <div className={className}>
            {label ? (
                <Label
                    variant="body"
                    className={`font-medium ${disabled ? 'ui-label-disabled' : 'ui-label'}`}
                >
                    {label}
                </Label>
            ) : null}
            <div className={resolvedEditorWrapperClassName} style={resolvedEditorWrapperStyle}>
                <MDXEditor
                    key={editorModeKey}
                    ref={editorRef}
                    markdown={markdown}
                    onChange={disabled || readOnly ? undefined : onChange}
                    readOnly={disabled || readOnly}
                    className={resolvedEditorClassName}
                    contentEditableClassName={contentEditableClassName}
                    plugins={plugins}
                />
            </div>
            {error ? (
                <Label variant="error" className="mt-2 ui-error">
                    {error}
                </Label>
            ) : null}
        </div>
    );
}
