import {
  Form,
  FormError,
  FieldError,
  Label,
  TextField,
  NumberField,
  SelectField,
  Submit,
} from '@redwoodjs/forms'

const GET_KATEGORIES = gql`
  query FindKategories {
    kategories {
      id
      name
    }
  }
`;

const ArtikelForm = (props) => {
  const onSubmit = (data) => {
    data.kategorie_id = parseInt(data.kategorie_id)
    props.onSave(data, props?.artikel?.id)
  }

  return (
    <div className="rw-form-wrapper">
      <Form onSubmit={onSubmit} error={props.error}>
        <FormError
          error={props.error}
          wrapperClassName="rw-form-error-wrapper"
          titleClassName="rw-form-error-title"
          listClassName="rw-form-error-list"
        />

        <Label
          name="name"
          className="rw-label"
          errorClassName="rw-label rw-label-error"
        >
          Name
        </Label>

        <TextField
          name="name"
          defaultValue={props.artikel?.name}
          className="rw-input"
          errorClassName="rw-input rw-input-error"
          validation={{ required: true }}
        />

        <FieldError name="name" className="rw-field-error" />

        <Label
          name="preis"
          className="rw-label"
          errorClassName="rw-label rw-label-error"
        >
          Preis
        </Label>

        <TextField
          name="preis"
          defaultValue={props.artikel?.preis}
          className="rw-input"
          errorClassName="rw-input rw-input-error"
          validation={{ valueAsNumber: true }}
        />

        <FieldError name="preis" className="rw-field-error" />

        <Label
          name="kategorie_id"
          className="rw-label"
          errorClassName="rw-label rw-label-error"
        >
          Kategorie id
        </Label>

        <SelectField name="kategorie_id"
          className="rw-input"
          errorClassName="rw-input rw-input-error"
          defaultValue={props.artikel?.kategorie_id} >
            {props.kategories.map((kategorie) => (
            <option key={kategorie.id} value={kategorie.id} >{kategorie.name}</option>
            ))}
        </SelectField>

        <FieldError name="kategorie_id" className="rw-field-error" />

        <div className="rw-button-group">
          <Submit disabled={props.loading} className="rw-button rw-button-blue">
            Save
          </Submit>
        </div>
      </Form>
    </div>
  )
}

export default ArtikelForm
