import { ErrorMessage, Field, Form, Formik } from 'formik'
import { Dispatch } from 'ketchup-react'
import { Action, chooseWonderAction, Player, State, wonders } from 'wonders-common'

export default function WonderSelector({ state, player, dispatch }: { state: State, player: Player, dispatch: Dispatch<Action> }) {
  function isWonderInUse(wonder: string) {
    return state.players.filter(p => p.name !== player.name).map(p => p.wonder).includes(wonder)
  }

  return <Formik
    initialValues={{ wonder: player.wonder ?? [...wonders.keys()][0] }}
    validate={values => {
      const errors: Partial<typeof values> = {}
      if (values.wonder.length === 0) {
        errors.wonder = 'Wonder not selected.'
      }
      if (isWonderInUse(values.wonder)) {
        errors.wonder = 'Wonder already in use.'
      }
      return errors
    }}
    onSubmit={({ wonder }) => dispatch(chooseWonderAction(player.name, wonder))}>
    <Form>
      <button type="submit">Choose wonder</button>
      {' '}
      <Field as="select" name="wonder">
        {[...wonders.keys()].map(w =>
          <option key={w} disabled={isWonderInUse(w)}>{w}</option>
        )}
      </Field>
      {' '}
      <ErrorMessage name="wonder" />
    </Form>
  </Formik>
}
