import FormControlLabel from '@material-ui/core/FormControlLabel'
import FormGroup from '@material-ui/core/FormGroup'
import { useTheme } from '@material-ui/core/styles'
import MuiSwitch, {
  SwitchProps as MuiSwitchProps,
} from '@material-ui/core/Switch/Switch'
import React, { FC, memo } from 'react'
import type { FieldRenderProps } from 'react-final-form'
import { Field, FieldProps } from '../lib/Field'

type SwitchHTMLElement = HTMLButtonElement

export type SwitchProps = MuiSwitchProps & { label: string }
export type SwitchBaseProps = SwitchProps &
  FieldRenderProps<any, SwitchHTMLElement>
export type ExposedSwitchProps = SwitchProps & FieldProps<SwitchHTMLElement>

const SwitchFieldBase: FC<SwitchBaseProps> = ({
  input: { value, type, ...restInput },
  label,
  ...custom
}) => {
  const theme = useTheme()
  return (
    <FormGroup row style={{ marginBottom: theme.spacing(1) }}>
      <FormControlLabel
        control={<MuiSwitch checked={value} {...restInput} {...custom} />}
        label={label}
      />
    </FormGroup>
  )
}
const FormSwitchField = memo(SwitchFieldBase)

export const SwitchField: FC<ExposedSwitchProps> = ({
  type = 'checkbox',
  color = 'primary',
  ...props
}) => {
  const render = (renderProps: FieldRenderProps<any, SwitchHTMLElement>) => (
    <FormSwitchField {...renderProps} {...props} />
  )

  return (
    <Field<any, FieldRenderProps<any, SwitchHTMLElement>, SwitchHTMLElement>
      type={type}
      color={color}
      render={render}
      {...props}
    />
  )
}
export default SwitchField
