import { createPortal } from 'react-dom'
import PropTypes from 'prop-types'
import { useState, useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { enqueueSnackbar as enqueueSnackbarAction, closeSnackbar as closeSnackbarAction } from 'store/actions'
import {
Box,
Typography,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Stack,
IconButton,
OutlinedInput,
Popover
} from '@mui/material'
import { useTheme } from '@mui/material/styles'
import { StyledButton } from 'ui-component/button/StyledButton'
// Icons
import { IconX, IconCopy } from '@tabler/icons'
// API
import apikeyApi from 'api/apikey'
// utils
import useNotifier from 'utils/useNotifier'
const APIKeyDialog = ({ show, dialogProps, onCancel, onConfirm }) => {
const portalElement = document.getElementById('portal')
const theme = useTheme()
const dispatch = useDispatch()
// ==============================|| Snackbar ||============================== //
useNotifier()
const enqueueSnackbar = (...args) => dispatch(enqueueSnackbarAction(...args))
const closeSnackbar = (...args) => dispatch(closeSnackbarAction(...args))
const [keyName, setKeyName] = useState('')
const [anchorEl, setAnchorEl] = useState(null)
const openPopOver = Boolean(anchorEl)
useEffect(() => {
if (dialogProps.type === 'EDIT' && dialogProps.key) {
setKeyName(dialogProps.key.keyName)
} else if (dialogProps.type === 'ADD') {
setKeyName('')
}
}, [dialogProps])
const handleClosePopOver = () => {
setAnchorEl(null)
}
const addNewKey = async () => {
try {
const createResp = await apikeyApi.createNewAPI({ keyName })
if (createResp.data) {
enqueueSnackbar({
message: 'New API key added',
options: {
key: new Date().getTime() + Math.random(),
variant: 'success',
action: (key) => (
)
}
})
onConfirm()
}
} catch (error) {
const errorData = error.response.data || `${error.response.status}: ${error.response.statusText}`
enqueueSnackbar({
message: `Failed to add new API key: ${errorData}`,
options: {
key: new Date().getTime() + Math.random(),
variant: 'error',
persist: true,
action: (key) => (
)
}
})
onCancel()
}
}
const saveKey = async () => {
try {
const saveResp = await apikeyApi.updateAPI(dialogProps.key.id, { keyName })
if (saveResp.data) {
enqueueSnackbar({
message: 'API Key saved',
options: {
key: new Date().getTime() + Math.random(),
variant: 'success',
action: (key) => (
)
}
})
onConfirm()
}
} catch (error) {
const errorData = error.response.data || `${error.response.status}: ${error.response.statusText}`
enqueueSnackbar({
message: `Failed to save API key: ${errorData}`,
options: {
key: new Date().getTime() + Math.random(),
variant: 'error',
persist: true,
action: (key) => (
)
}
})
onCancel()
}
}
const component = show ? (
) : null
return createPortal(component, portalElement)
}
APIKeyDialog.propTypes = {
show: PropTypes.bool,
dialogProps: PropTypes.object,
onCancel: PropTypes.func,
onConfirm: PropTypes.func
}
export default APIKeyDialog