import { Cached } from '@mui/icons-material'
import { Box, CardActions, IconButton, Typography } from '@mui/material'
import { toast } from 'react-toastify'
import axios from '../../../config/axios'
import { EditButton } from '../../IconButtons'
import { DrawerButton } from '../../ModalButtons'
import { DatabaseConfigurationForm } from '../DatabaseConfigurationForm'
import { StyledCard, StyledCardContent } from '../styles'

export const ConnectionCard = ({ data }) => {
  const handleReconnect = async () => {
    const response: string = await axios.post(
      'hrms/punch-logs-database-config/connect',
      {},
    )
    if (response) {
      window.location.reload()
    }
    toast.success(response)
  }
  return (
    <>
      <StyledCard>
        <StyledCardContent>
          <Column label={'Host'} value={data?.host} />
          <Column label={'Username'} value={data?.username} />
          <Column label={'Password'} value={data?.password} />
          <Column label={'Port'} value={data?.port} />
          <Column label={'Database'} value={data?.database} />
          <Column label={'Timezone'} value={data?.timezone} />
          <Column
            label={'Status'}
            value={data?.connectionStatus}
            color={data?.connectionStatus == 'Connected' ? 'green' : 'red'}
          />
        </StyledCardContent>
        <CardActions>
          <DrawerButton
            key={'1'}
            anchor={({ open }) => <EditButton onClick={open} />}
            content={({ close }) => (
              <DatabaseConfigurationForm
                data={data}
                close={close}
                successToastMessage="Updated Database Configuration"
                type={data.type}
              />
            )}
            title="Add Database Configuration"
          />
          <IconButton onClick={handleReconnect}>
            <Cached sx={{ '&:hover': { color: 'green' } }} />
          </IconButton>
        </CardActions>
      </StyledCard>
    </>
  )
}

export const Column = ({
  label,
  value,
  color = '#000000',
}: {
  label: string
  value: string
  color?: string
}) => {
  return (
    <Box>
      <Typography sx={{ fontSize: 14 }} color="text.secondary" gutterBottom>
        {label}
      </Typography>
      <Typography variant="h5" component="div" color={color}>
        {value}
      </Typography>
    </Box>
  )
}
