import * as React from 'react'

import { flow, filter, take } from 'lodash/fp'

const getFirstError = (stateErrors: Array<string>, fieldErrors: Array<string>) => {
  // Convert the state errors to a set for constant-time membership checks
  const errorSet = new Set(stateErrors)

  // get the first error that matches in the field error set, lazily
  return flow(
    filter((e: string) => errorSet.has(e)),
    take(1)
  )(fieldErrors)
}

interface ErrorProps {
  stateErrors: Array<string>
  fieldErrors: Array<string>
  ignoreErrors?: boolean
  modal?: boolean
}

export const Errors = ({
  stateErrors,
  fieldErrors,
  ignoreErrors = false,
  modal = false
}: ErrorProps) => {
  const errorMsg = ignoreErrors || getFirstError(stateErrors, fieldErrors)[0]
  const classPostfix = modal ? 'modal-field-error' : 'field-error'

  return errorMsg
    ? (
      <div className={ `yes-${classPostfix}` }>{ errorMsg }</div>
    )
    : (
      <div className={ `no-${classPostfix}` }></div>
    )
}
