'use client';

/**
 * @author: Kim Jino
 * @since: 2025.03.31
 * @description: CKEditor component for Next.js using Script component for loading CKEditor script
 */

import '@/styles/editor.scss';
import Script from 'next/script';
import React, { useRef, useState, useEffect, useCallback, useMemo } from 'react';
import { CKEditor } from '@ckeditor/ckeditor5-react';
import type { Editor as CKEditorInstance } from 'ckeditor5';
import Loading from '@/app/component/Loading';

interface EditorProps {
	data?: string;
	onChange?: (data: string) => void;
}

export default function Editor({ data = '', onChange }: EditorProps)
{
	const editorRef = useRef<typeof window.Editor|null>(null);
	const [ready, setReady] = useState(false);

	useEffect(() => {
		if (typeof window !== 'undefined' && window.Editor) {
			editorRef.current = window.Editor;
			setReady(true);
		}
	}, []);

	const handleScriptLoad = () => {
		if (typeof window !== 'undefined' && window.Editor) {
			editorRef.current = window.Editor;
			setReady(true);
		} else {
			console.error('CKEditor script not loaded properly.');
		}
	};

	const editorConfig = useMemo(() => ({
		placeholder: '내용을 입력하세요.',
		maxWordCount: 3000,

		// 이미지 설정
		allowImage: true,
		imageUploadLimit: 1,
		imageUploadMaxSize: 5120,

		// 미디어어 설정
		allowMedia: true,
		mediaUploadLimit: 1
	}), []);

	const handleReady = useCallback((editor: CKEditorInstance) => {
		console.log('Editor was initialized');

		// 최소 높이 설정
		editor.editing.view.change(writer => {
			const root = editor.editing.view.document.getRoot();
			if (root) {
				writer.setStyle('min-height', '300px', root);
			}
		});
	}, []);

	const handleChange = useCallback((_: unknown, editor: CKEditorInstance) => {
		onChange?.(editor.getData());
	}, [onChange]);

	return (
		<>
			<Script src="/editor/editor.min.js" strategy="afterInteractive" onLoad={handleScriptLoad}/>

			{ready && editorRef.current ? (
				<CKEditor
					editor={editorRef.current}
					data={data}
					config={editorConfig}
					onReady={handleReady}
					onChange={handleChange}
				/>
			) : (
				<Loading/>
			)}
		</>
	);
}