import { memo, useCallback, useState } from 'react'
import { Upload, Button } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { UploadFile } from 'antd/lib/upload/interface'

import { upload } from  './factory'
import { ErrorFetch } from './ErrorFetch'

export type UploadFormProps = {
  url: string
  disabled?: boolean
  accept?: string
  style?: CSSStyleSheet
  formData: FormData
  onUploadStart?: () => void
  onUploadSuccess?: () => void
  onUploadComplete?: () => void
  onUploadError?: (error: unknown) => void
}

export const UploadForm = memo<UploadFormProps>(({ url, disabled, accept, style, formData, onUploadStart, onUploadSuccess, onUploadComplete, onUploadError }) => {
  const [fileList, setfileList] = useState<UploadFile<any>[]>([])

  const handleFileSend = useCallback(async () => {
    onUploadStart?.()
    try {
      const formDataLocal = new FormData()
      fileList.forEach((val) => formDataLocal.append('files', String(val.originFileObj)))

      if(formData)
        for(const propName in formData)
          formDataLocal.append(propName, String(formData.get(propName)))

      const response = await upload(url, formDataLocal)
      if (!response.ok) {
        const errorText = await response.text()
        const error = new ErrorFetch(response.status, errorText)
        throw error
      } else {
        onUploadSuccess?.()
      }
    } catch(error) {
      if(process.env.NODE_ENV === 'development')
        console.error(error)
      onUploadError?.(error)
    } finally {
      setfileList([])
      onUploadComplete?.()
    }
  }, [fileList, formData, onUploadComplete, onUploadError, onUploadStart, onUploadSuccess, url])

  const isSendButtonEnabled = fileList.length > 0
  return(
    <div style={{ display: 'flex', ...style }}>
      <Upload
        name={'file'}
        accept={accept}
        disabled={disabled}
        fileList={fileList}
        onChange={(props) => setfileList(props.fileList)}
      >
        <Button disabled={disabled} icon={<UploadOutlined/>}>Загрузить файл</Button>
      </Upload>
      <Button
        type={'primary'}
        onClick={handleFileSend}
        disabled={!isSendButtonEnabled}
        style={{ marginLeft: '10px', display: isSendButtonEnabled ? '' : 'none' }}
      >
        Отправить
      </Button>
    </div>
  )
})

export default UploadForm
