import { Box, Button, ButtonProps, CircularProgress } from '@mui/material'
import { AxiosResponse } from 'axios'
import { useState } from 'react'
import { useMutation } from 'react-query'
import { toast } from 'react-toastify'
import { axiosErrorToast } from '../../config/axios'
import ExcelToJsonInput from './ExcelToJsonInput'

interface ExcelJsonUploadProps {
  postFn: (json) => Promise<AxiosResponse<any, any>>
  btnProps?: ButtonProps
}

export default function ExcelJsonUpload({
  postFn,
  btnProps,
}: ExcelJsonUploadProps) {
  const [json, setJson] = useState([])
  const { mutate, isLoading } = useMutation(postFn, {
    onSuccess(data) {
      toast.success('Data uploaded successfully')
    },
    onError(error) {
      axiosErrorToast(error)
    },
  })

  const onSubmit = () => {
    mutate(json)
  }

  return (
    <Box>
      <Button
        sx={{ marginBottom: '20px' }}
        onClick={onSubmit}
        endIcon={isLoading ? <CircularProgress size={20} /> : null}
        disabled={isLoading}
        {...btnProps}
      >
        Submit Data
      </Button>
      <ExcelToJsonInput
        onChange={(jsonValue) => {
          setJson(jsonValue)
        }}
      />
    </Box>
  )
}
