import { Add, Close } from '@mui/icons-material'
import {
  Box,
  Button,
  ButtonProps,
  CircularProgress,
  Dialog,
  DialogContent,
  DialogProps,
  IconButton,
  Typography,
  alpha,
  styled,
} from '@mui/material'
import { ReactNode, useEffect, useRef, useState } from 'react'
import { toast } from 'react-toastify'
import axios from '../../config/axios'
import { buffertoCSV } from '../../utils'
import { useErrorModal } from '../ErrorModalWrapper/ErrorModalWrapper'
import { DeleteButton, EditButton } from '../IconButtons'
import { getAccept } from '../UploadButton/UploadButton'
import { UploadButtonProps } from '../UploadButton/types'
const animatedImage = require('./AnimatedUploadFile.gif')

const StyledDialogHeader = styled(Box)(({ theme }) => ({
  height: '64px',
  backgroundColor: alpha(theme.palette.text.secondary, 0.1),
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
  padding: '0.6rem 1rem',
}))
const StyledDialogContent = styled(DialogContent)(({ theme }) => ({
  display: 'flex',
  flexDirection: 'column',
  gap: '1rem',
  alignItems: 'center',
  padding: '40px',
}))

const StyledImage = styled((props: any) => (
  <Box>
    <img {...props} />
  </Box>
))(({ theme }) => ({
  height: '90px',
  width: '90px',
  '> img': {
    width: '100%',
    height: '100%',
    objectFit: 'contain',
  },
}))

const StyledChooseFileButton = styled(Button)(({ theme }) => ({
  padding: '15px 20px',
  height: '50px',
  '> .MuiBox-root': {
    display: 'flex',
    width: '100%',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
}))

const StyledFileLabel = styled(Box)(({ theme }) => ({
  background: theme.palette.secondary.light,
  borderRadius: '5px',
  padding: '16px',
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
}))

interface UploadFileDialogProps {
  buttonProps?: ButtonProps
  dialogProps?: DialogProps
  buttonText: string | ReactNode
  children?: ReactNode
  dialogTitle: ReactNode | string
  sampleFileUrl?: string
  sampleFileDownloadUrl?: string
  uploadUrl: string
  successMessage?: string
  refetchFn?: (res: any) => void
  onUpload?: () => void
  postBody?: { [key: string]: string | any }
  type?: UploadButtonProps['type']
}

export default function UploadFileDialog({
  buttonProps,
  dialogProps,
  buttonText,
  dialogTitle,
  uploadUrl,
  sampleFileUrl,
  successMessage,
  refetchFn,
  sampleFileDownloadUrl,
  postBody = {},
  onUpload,
  type = 'excel',
}: UploadFileDialogProps) {
  const inputRef: any = useRef(null)
  const [loading, setLoading] = useState(false)
  const errorModal = useErrorModal()
  const [file, setFile] = useState(null)
  const [open, setOpen] = useState(false)
  const onClose = () => {
    setOpen(false)
  }

  const triggerUpload = () => {
    if (!inputRef.current) return
    inputRef?.current?.click()
  }

  const handleImageChange = (e) => {
    setFile(e.target.files[0])
  }

  const handleOnUpload = () => {
    onUpload && onUpload()
    if (!file) return ``
    const formData = new FormData()
    formData.append('file', file)
    if (postBody) {
      Object.keys(postBody).forEach((key) => {
        formData.append(key, postBody[key])
      })
    }
    setLoading(true)

    axios
      .post(uploadUrl, formData)
      .then((res) => {
        setLoading(false)
        refetchFn && refetchFn(res)
        setOpen(false)
        toast.success(successMessage ?? 'Successful')
        setFile(null)
      })
      .catch((err) => {
        // eslint-disable-next-line no-console
        console.log(err)
        setLoading(false)
        // axiosErrorToast(err)
        errorModal({ error: err })
      })
  }

  const handleSampleFileDownload = async () => {
    try {
      const res = await axios.get(sampleFileDownloadUrl)
      buffertoCSV({ data: res.data, filename: `${dialogTitle}` })
    } catch (error) {
      errorModal({ error: error })
      // axiosErrorToast(error)
    }
  }

  useEffect(() => {
    return () => {
      setFile(null)
      inputRef.current = null
    }
  }, [])

  return (
    <>
      <Button
        onClick={() => {
          setOpen(true)
        }}
        variant="outlined"
        {...buttonProps}
      >
        {buttonText}
      </Button>
      <Dialog
        open={open}
        onClose={onClose}
        maxWidth="sm"
        fullWidth
        {...dialogProps}
      >
        <StyledDialogHeader>
          <Typography fontWeight={600}>{dialogTitle}</Typography>
          <IconButton onClick={onClose}>
            <Close />
          </IconButton>
        </StyledDialogHeader>
        <StyledDialogContent>
          <StyledImage src={animatedImage} alt="Upload Image" />
          <Typography variant="h6">{dialogTitle}</Typography>
          <Typography textAlign={'center'}>
            Before importing, download Sample CSV File or Sample XLSX file and
            compare it with your sheet or edit the sample sheet
          </Typography>
          <Box sx={{ minWidth: '400px', marginBottom: '20px' }}>
            {!file ? (
              <>
                <input
                  onChange={handleImageChange}
                  hidden
                  accept={getAccept(type)}
                  type={'file'}
                  ref={inputRef}
                />
                <StyledChooseFileButton
                  variant="outlined"
                  fullWidth
                  onClick={triggerUpload}
                >
                  <Box>
                    <Typography variant="h6" color="primary">
                      Choose File
                    </Typography>
                    <Add />
                  </Box>
                </StyledChooseFileButton>
              </>
            ) : (
              <StyledFileLabel>
                <Typography variant="body2">{file?.name}</Typography>
                <Box display={'flex'} gap="16px">
                  <EditButton
                    onClick={() => {
                      triggerUpload()
                    }}
                  />
                  <DeleteButton onClick={() => setFile(null)} />
                </Box>
              </StyledFileLabel>
            )}
          </Box>

          <Button
            fullWidth
            sx={{ maxWidth: '255px' }}
            onClick={handleOnUpload}
            endIcon={
              loading ? (
                <CircularProgress size={20} sx={{ color: 'white' }} />
              ) : null
            }
          >
            Upload File
          </Button>
          {sampleFileUrl && (
            <a href={sampleFileUrl} target="_blank" rel="noreferrer">
              <Button fullWidth sx={{ maxWidth: '255px' }} variant="outlined">
                Download Sample File
              </Button>
            </a>
          )}
          {sampleFileDownloadUrl && (
            <Button variant="outlined" onClick={handleSampleFileDownload}>
              Download Sample File
            </Button>
          )}
        </StyledDialogContent>
      </Dialog>
    </>
  )
}
