import { Modal, Popover, Tooltip } from 'antd';
import DOMPurify from 'dompurify';
import { useState } from 'react';

export interface IRemarkFormItemProps {
	remark?: string;
	ghost?: boolean;
	mode?: 'modal' | 'popover' | 'tooltip' | 'detail';
}

const RichTextRenderer = ({ htmlContent }: any) => {
	const sanitizedContent = DOMPurify.sanitize(htmlContent, {
		// ALLOWED_TAGS: ['p', 'b', 'i', 'em', 'strong', 'a', 'span'], // 允许的标签白名单
		// ALLOWED_ATTR: ['href', 'title'], // 允许的属性
	});
	return (
		<div
			className="rich-text-content"
			dangerouslySetInnerHTML={{ __html: sanitizedContent }}
		/>
	);
};

export default function RemarkFormItem(props: IRemarkFormItemProps) {
	const { remark, ghost = false, mode = 'detail' } = props;

	const [open, setOpen] = useState<boolean>(false);

	if (ghost) {
		return remark;
	}
	if (!remark) {
		return '';
	}

	if (remark.length > 500 || mode === 'modal') {
		return (
			<>
				<Modal
					width={'800px'}
					open={open}
					onOk={() => setOpen(false)}
					onCancel={() => setOpen(false)}
					footer={false}
				>
					<RichTextRenderer htmlContent={remark} />
				</Modal>
				<span
					style={{ cursor: 'pointer', color: '#1890ff' }}
					onClick={() => setOpen(true)}
				>
					{remark.includes('<') ? '查看' : `${remark.substring(0, 20)}...`}
				</span>
			</>
		);
	}

	if (remark.length > 200 || mode === 'popover') {
		return (
			<Popover content={<RichTextRenderer htmlContent={remark} />}>
				<span style={{ cursor: 'pointer', color: '#1890ff' }}>
					{remark.includes('<') ? '查看' : `${remark.substring(0, 20)}...`}
				</span>
			</Popover>
		);
	}

	return (
		<Tooltip title={<RichTextRenderer htmlContent={remark} />}>
			<span style={{ cursor: 'pointer', color: '#1890ff' }}>
				{remark.includes('<') ? '查看' : `${remark.substring(0, 20)}...`}
			</span>
		</Tooltip>
	);
}
