import React, {useMemo, useState} from 'react'
import { HotModal } from './component'
import { Hot, hotAdded } from '../../store/hots'
import { nanoid } from '@reduxjs/toolkit'
import { useDispatch } from 'react-redux'
import { Input } from 'antd'
import Upload from '../../components/Upload'
import style from './style.module.css'
import { useForm } from 'antd/lib/form/Form'

export type Props = {
  onClose: () => void,
  pos: Hot['pos']
}

export function AddHot(props: Props) {
  const [file, setFile] = useState<File>()
  const [form] = useForm<Hot>()
  const dispatch = useDispatch()
  const meta = useMemo(() => {
    if (file) {
      return {
        name: file.name,
        type: file.type.substring(0, file.type.indexOf('/')),
        url: URL.createObjectURL(file)
      }
    }
  }, [file])
  const metaEle = {
    'image': <img src={meta?.url} alt={meta?.name} />
  }
  
  const items = [
    {
      label: '请输入热点标题',
      ele: <Input />,
      name: 'title',
    },
    {
      label: '请输入热点内容',
      ele: <Input.TextArea />,
      name: 'content',
    },
    {
      label: '请输入上传照片或视频',
      ele: (
        <div className={style.meta}>
          <Upload upHandle={setFile} text={`点击${file ? '替换' : '上传'}`} />
          {meta?.type && metaEle[meta.type]}
        </div>
      )
    },
    {
      label: '请输入外链',
      ele: <Input />,
      name: 'link',
    },
  ]

  const onSubmit = () => {
    dispatch(
      hotAdded({
        ...form.getFieldsValue(),
        pos: props.pos,
        meta: meta,
        id: nanoid()
      })
    )
    props.onClose()
  }

  return <HotModal 
    title="添加热点" 
    items={items} 
    form={form}
    enter={onSubmit} 
    cancel={props.onClose}
  />
}