import React, { useMemo, useEffect, useState } from 'react'
import TpmMdEditor from '../tpm/challengesnew/tpm-md-editor'
import './CommentItemMDEditor.css';
import mediator from '../../common/mediator';

export default ({ item, replyComment, showReplyEditorFlag, currentReplyComment, buttonText = '发送' }) => {
	const [active, setActive] = useState(showReplyEditorFlag)
	const [value, setValue] = useState('')

	function onHandleChange(v) {
		setValue(v)
	}

	async function onCommit() {
		await replyComment(value, item.id)
		setValue('')
		setActive(false)
	}

	useEffect(() => {
		const unSub = mediator.subscribe('cancel-editor', () => {
			if (active) {
				setActive(false)
			}
		})
		return unSub
	}, [item, active])

	const isShow = useMemo(() => {
		let rs = false
		if (currentReplyComment && item && item.id === currentReplyComment.id) {
			rs = true
		}
		return rs
	}, [currentReplyComment, item])

	useEffect(() => {
		if (active && active !== showReplyEditorFlag) {
			setActive(false)
		} else {
			setActive(isShow)
		}
	}, [isShow, showReplyEditorFlag])



	return (
		<div className='comment-item-editor' style={{ display: active ? 'block' : 'none', width: '100%' }}>
			<TpmMdEditor className='mini' startInit={isShow} initValue={value} mdID={item.id} noStorage={true} watch={false} height={155} placeholder='我要回复' showResizeBar={true} onChange={onHandleChange} />
			<a onClick={onCommit} className="commentsbtn task-btn task-btn-blue fr" > {buttonText} </a>
		</div>
	)
}