import { MaterialModal } from '@/components';
import { IDomEditor } from '@wangeditor-next/editor';
import { useEffect, useState } from 'react';

export default function CsModal(props: {
	onInit?: (setOpen: (open: boolean) => void) => void;
	editor: IDomEditor;
}) {
	const { onInit, editor } = props;
	const [open, setOpen] = useState(true);

	useEffect(() => {
		onInit?.(setOpen);
	}, []);

	// @ts-ignore
	return (
		<MaterialModal
			type={'radio'}
			maxCount={1}
			open={open}
			destroyOnHidden={true}
			onOk={() => setOpen(false)}
			onCancel={() => setOpen(false)}
			onFinish={(materialList) => {
				const material = materialList?.[0];
				if (!material) return;
				// 重要，需要聚焦，否则无法插入
				editor.focus();
				if (material.type === 'FILE_VIDEO') {
					editor.dangerouslyInsertHtml(
						`<audio controls src="${material?.url}" alt="${material?.name}"/>`,
					);
				}
				if (material.type === 'FILE_IMAGE') {
					editor.dangerouslyInsertHtml(
						`<img src="${material?.url}" alt="${material?.name}"/>`,
					);
				}
			}}
		/>
	);
}
