import { TextField as SimpleTextField } from '@mui/material'
import { Field } from 'formik'
import { TextField } from 'formik-mui'
import { ChangeEvent, ReactElement } from 'react'
import { makeStyles } from 'tss-react/mui'

interface Props {
  name: string
  label: string
  password?: boolean
  formik?: boolean
  optional?: boolean
  defaultValue?: string
  placeholder?: string
  onChange?: (event: ChangeEvent<HTMLTextAreaElement>) => void
}

const useStyles = makeStyles()(theme => ({
  field: {
    background: theme.palette.background.paper,
    '& fieldset': {
      border: 0,
    },
    '& .Mui-focused': {
      background: theme.palette.background.paper,
    },
    '& .MuiInputBase-root': {
      background: theme.palette.background.paper,
    },
    '& .MuiFilledInput-root': {
      borderRadius: 0,
    },
  },
}))

export function SwarmTextInput({
  name,
  label,
  password,
  optional,
  formik,
  onChange,
  defaultValue,
  placeholder,
}: Props): ReactElement {
  const { classes } = useStyles()

  if (formik) {
    return (
      <Field
        component={TextField}
        type={password ? 'password' : undefined}
        required={!optional}
        name={name}
        label={label}
        fullWidth
        variant="filled"
        className={classes.field}
        defaultValue={defaultValue || ''}
        InputProps={{ disableUnderline: true }}
        placeholder={placeholder}
      />
    )
  }

  return (
    <SimpleTextField
      type={password ? 'password' : undefined}
      required
      label={label}
      fullWidth
      variant="filled"
      className={classes.field}
      defaultValue={defaultValue || ''}
      onChange={onChange}
      InputProps={{ disableUnderline: true }}
      placeholder={placeholder}
    />
  )
}
