import { ErrorMessage, Field, Form, Formik } from 'formik';
import { Dispatch, useState } from 'react';
import sample from 'lodash/sample'
import Row from 'react-bootstrap/Row';

const namePlaceholders = [
  'Alexander the Great',
  'Genghis Khan',
  'Boudicca',
  'Cleopatra',
  'Alaric the Visigoth',
  'Cyrus the Great',
  'Augustus',
  'Hannibal',
  'Tutankhamen',
]

export default function UserSelector({ users, user, selectUser, removeUser, locked }: {
  users: string[], user?: string, selectUser: Dispatch<string | undefined>, removeUser: () => void, locked: boolean
}) {
  const [namePlaceholder] = useState(() => sample(namePlaceholders))
  return <Row>
    {user
      ? <>Playing as {user} <button onClick={() => selectUser(undefined)}>Change</button> <button onClick={removeUser} disabled={locked}>Remove</button></>
      : <Formik
          initialValues={{ newUser: '' }}
          validate={values => {
            const errors: Partial<typeof values> = {}
            if (values.newUser.length === 0) {
              errors.newUser = 'Name cannot be blank.'
            }
            return errors
          }}
          onSubmit={(values) => {
            selectUser(values.newUser)
          }}
        >{() => <Form>
          <button type="submit">Play as</button>
          <Field type="text" name="newUser" placeholder={namePlaceholder}/> <ErrorMessage name="newUser"/>
        </Form>}
      </Formik>
    }
  </Row>
}
