import React, { useState, useEffect } from 'react'
import './comment-input.scss'
import TpmMdEditor from '../tpm/challengesnew/tpm-md-editor'
import mediator from '../../common/mediator'

export default ({
  challenge,
  praisePlus,
  tabIndexChange,
  createNewComment
}) => {
  const [showMd, setShowMd] = useState(false)
  const [value, setValue] = useState('')

  function onChangeHandler(v) {
    setValue(v)
  }

  useEffect(() => {
    const unSub = mediator.subscribe('cancel-editor', () => {
      if (showMd) {
        setShowMd(false)
      }
    })
    return unSub
  }, [challenge, showMd])

  function onShowMd() {
    setShowMd(true)
  }

  function onCancel() {
    setShowMd(false)
  }

  async function onCommit() {
    await createNewComment(value)
    setValue('')
    setShowMd(false)
    tabIndexChange(3)
  }

  return (
    <div className="comment-input-editor-container">
      <div className={showMd ? 'text-area hide' : 'text-area'}>
        <input placeholder='说点什么' onClick={onShowMd}></input>
        <a className="color-grey" onClick={praisePlus} title={challenge.user_praise ? "取消点赞" : "点赞"}>
          <i className={`mr3  ${challenge.user_praise ? "iconfont icon-dianzan color-orange03" : "iconfont icon-dianzan-xian"} `} alt="赞" ></i>
          {challenge.praise_count ? <span>{challenge.praise_count}</span> : ''}
        </a>
      </div>
      <div className={showMd ? "md-container" : 'md-container hide'}>
        <TpmMdEditor mdID={challenge.shixun_id} className='mini' startInit={showMd} watch={false} noStorage={true} initValue={value} height={240} onChange={onChangeHandler} />
        <div className="tip-container" onClick={onCancel}>
          <p>请勿粘贴答案，否则将造成账号禁用后果！</p>
          <a className='btn-send' onClick={onCommit}>发送</a>
        </div>
      </div>
    </div>
  )
}