import { Form, Upload, Button} from 'antd'
import { UploadOutlined} from '@ant-design/icons'
import { useState } from 'react'
import { upload } from  './factory'

export default function UploadForm({url, onUploadStart, onUploadComplete, onUploadError}) {  
  const [isSubmitButtonEnabled, setSubmitButtonEnabled] = useState(false)  
  const [form] = Form.useForm();

  const handleFileSend = async (values) => {
    if(onUploadStart)
      onUploadStart()
    try {
      const values = await form.validateFields();      
      const formData = new FormData()
      values.file.fileList.forEach((val) => {
        formData.append("files", val.originFileObj);
      });
      await upload(url, formData)
    } catch(error) {
      if(onUploadError)
      onUploadError(error)
    } finally {
      form.resetFields()
      if(onUploadComplete)
        onUploadComplete()
    }
  }

  return(
    <Form
      form={form}
      onFinish={handleFileSend}
      style={{display: 'flex'}}>
      <Form.Item 
        name="file" 
        style={{marginBottom: 0}}
        rules={[{ required: true, message: 'Выберите файл' }]}>
        <Upload 
          name ="file"               
          onChange={(props) => setSubmitButtonEnabled(props.fileList.length > 0)}>
          <Button icon={<UploadOutlined/>}>Загрузить файл</Button>
        </Upload>
      </Form.Item>
      <Form.Item style={{marginBottom: 0}}>
        <Button 
          type="primary" 
          htmlType="submit"
          disabled={!isSubmitButtonEnabled}
          style={{marginLeft: '10px', display:isSubmitButtonEnabled?'':'none'}}>
          Отправить
        </Button>
      </Form.Item>
    </Form>
  )
} 