import { Button, CircularProgress, styled } from '@mui/material'
import { useRef, useState } from 'react'
import { toast } from 'react-toastify'
import axios from '../../config/axios'
import { UploadButtonProps } from './types'

export const getAccept = (type: UploadButtonProps['type']) => {
  switch (type) {
    case 'file':
      return '.xlsx,.xls,.doc, .docx,.ppt, .pptx,.txt,.pdf'
    case 'image':
      return 'image/*'
    case 'video':
      return 'video/*'
    case 'audio':
      return 'audio/*'
    case 'excel':
      return '.xlsx,.xls,.csv'
  }
}

export default function UploadButton({
  type,
  onChange,
  uploadUrl,
  onSuccess,
  styledUpload,
  loadingState,
  refetchFn,
}: UploadButtonProps) {
  const [loading, setLoading] = useState<boolean>(false)

  const formRef: any = useRef()
  const fileInputRef: any = useRef()
  const ref: any = useRef()
  const handleChange = (e: any) => {
    if (e.target.files[0]) {
      const formData = new FormData()
      formData.append('file', e.target.files[0])
      setLoading(true)
      loadingState && loadingState(true)
      axios
        .post(uploadUrl, formData)
        .then((res) => {
          onChange({
            url: res.data.url,
            key: res.data.key,
            type: type,
            fileName: res.data?.mediaObject?.originalFileName ?? '',
            id: res.data?.mediaObject?.id ?? '',
            mediaObject: res?.data?.mediaObject,
          })
          refetchFn && refetchFn()
          setLoading(false)
          loadingState && loadingState(false)
          if (onSuccess) onSuccess()
          !styledUpload && formRef?.current?.reset()
        })
        .catch((err) => {
          setLoading(false)
          loadingState && loadingState(false)
          toast.error(
            err?.response?.data?.message ?? 'Server Error While Uploading File',
          )
          !styledUpload && formRef?.current?.reset()
        })
    }
  }

  return (
    <>
      {styledUpload ? (
        <>
          <div
            onClick={() => {
              ref.current.click()
            }}
          >
            {styledUpload}
          </div>
          <input
            accept={getAccept(type)}
            type="file"
            hidden
            ref={ref}
            onChange={handleChange}
          />
        </>
      ) : (
        <>
          <form ref={formRef}>
            <input
              ref={fileInputRef}
              type="file"
              style={{ display: 'none' }}
              accept={getAccept(type)}
              onChange={handleChange}
            />
            <StyledButton
              fullWidth
              endIcon={loading ? <CircularProgress size={16} /> : null}
              variant="outlined"
              disabled={loading}
              size={'large'}
              onClick={() => fileInputRef.current.click()}
            >
              {getLabel(type)}
            </StyledButton>
          </form>
        </>
      )}
    </>
  )
}

const getLabel = (type) => {
  switch (type) {
    case 'file':
      return 'File'
    case 'image':
      return 'Image'
    case 'video':
      return 'Video'
    case 'audio':
      return 'Audio'
  }
}

const StyledButton = styled(Button)(({ theme }) => ({}))
