import React, { useEffect, useRef, useState } from 'react'
import { Button, Icon, Modal } from 'antd'
import Selector from './Selector'

export default (props) => {
  const { value, placeholder, onChange } = props;

  const [visible, setVisible] =  useState(false)
  const [title, setTitle] = useState(placeholder)
  const roomRef = useRef()

  const handleSubmit = () => {
    if (onChange) {
      if (!roomRef.current) {
        onChange(undefined)
      } else {
        onChange(JSON.stringify(roomRef.current))
      }
    }
    setVisible(false)
  }

  useEffect(() => {
    if (value) {
      const room = JSON.parse(value)
      setTitle(room.theme || '[直播间无名称]')
    } else {
      setTitle(placeholder)
    }
  }, [value])

  return (
    <>
      <Button type="link" onClick={() => setVisible(true)}>
        <span>{title} </span>
        <Icon type="right" />
      </Button>
      <Modal title="选择直播间" visible={visible} onOk={handleSubmit} onCancel={() => setVisible(false)}>
        <Selector onChange={(room) => roomRef.current = room} />
      </Modal>
    </>
  )
}
