import AttachFileIcon from '@mui/icons-material/AttachFile'
import { CircularProgress, styled, Typography } from '@mui/material'
import { ReactNode, useRef, useState } from 'react'
import { toast } from 'react-toastify'
import axios from '../config/axios'

export default function UploadDocument({
  accept = '.doc,.docx,.pdf',
  styledUpload,
  postUrl,
  postBody,
  styleProps,
  onSuccess,
  onError,
  width,
  height,
}: {
  accept?: string
  styledUpload?: ReactNode
  postUrl: string
  postBody?: object
  onSuccess?: (res: any) => void
  onError?: (res: any) => void
  styleProps?: any
  width?: string
  height?: string
}) {
  const [loading, setLoading] = useState(false)
  const fileRef = useRef<any>()

  const handleChange = (e) => {
    if (e.target.files[0]) {
      const formData = new FormData()
      formData.append('file', e.target.files[0])
      if (postBody) {
        Object?.keys(postBody)?.forEach((key) => {
          formData?.append(key, postBody[key])
        })
      }

      setLoading(true)
      axios
        .post(postUrl, formData)
        .then((res) => {
          setLoading(false)
          onSuccess(res?.data)
        })
        .catch((err) => {
          onError && onError(err)
          setLoading(false)
          toast.error('Server Error While Uploading File')
        })
    }
  }

  return (
    <>
      {styledUpload ? (
        <div
          onClick={() => {
            fileRef.current.click()
          }}
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            ...styleProps,
          }}
        >
          {loading ? <CircularProgress size={30} /> : styledUpload}
        </div>
      ) : (
        <StyledImageLabel
          onClick={() => {
            fileRef.current.click()
          }}
        >
          <AttachFileIcon />
          <Typography sx={{ opacity: '0.6' }}>
            {loading ? 'Uploading...' : `Upload File`}
          </Typography>
        </StyledImageLabel>
      )}
      <input
        type="file"
        ref={fileRef}
        style={{ display: 'none' }}
        accept={accept}
        onChange={handleChange}
      />
    </>
  )
}

export const StyledImageLabel = styled('div')(({ theme }) => ({
  cursor: 'pointer',
  borderRadius: '10px',
  width: '100%',
  height: '150px',
  border: '1px dashed #0000001A',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'center',
  alignItems: 'center',
  '&:hover': {
    backgroundColor: '#EFEFEF',
  },
  '& > *': {
    color: theme.palette.text.disabled,
  },
}))
