import React, { FC } from 'react'

import FormField from './form-field'


type FormEmailFieldProps = {
  id?: string,
  invalidMessage?: string,
  label: string,
  name?: string,
  optional?: boolean,
  setValid(valid: boolean): void,
  setValue(value: string): void,
  [other:string]: unknown
}

const isEmailFieldValid = (elem: HTMLInputElement): boolean => {
  if (elem.value && /^[\S]+@[\S]+\.[\S]{2,4}$/.test(elem.value)) {
    return true
  }

  return false
}

const FormEmailField:FC<FormEmailFieldProps> = ({
  id,
  invalidMessage="Invalid email address.",
  label,
  optional=false,
  name,
  setValid,
  setValue,
  ...other
}: FormEmailFieldProps) => {
  return (
    <FormField
      id={id}
      invalidMessage={invalidMessage}
      label={label}
      name={name}
      optional={optional}
      setValid={setValid}
      setValue={setValue}
      type="email"
      validator={isEmailFieldValid}
      {...other}
    />
  )
}

export default FormEmailField
