import { navigate, routes } from '@redwoodjs/router'
import { useMutation } from '@redwoodjs/web'
import { toast } from '@redwoodjs/web/toast'

import KaufForm from 'src/components/Kauf/KaufForm'

const CREATE_KAUF_MUTATION = gql`
  mutation CreateKaufMutation($input: CreateKaufInput!) {
    createKauf(input: $input) {
      id
    }
  }
`

const NewKauf = () => {
  const [createKauf, { loading, error }] = useMutation(CREATE_KAUF_MUTATION, {
    onCompleted: () => {
      toast.success('Kauf created')
      navigate(routes.kaufs())
    },
    onError: (error) => {
      toast.error(error.message)
    },
  })

  const onSave = (input) => {
    createKauf({ variables: { input } })
  }

  return (
    <div className="rw-segment">
      <header className="rw-segment-header">
        <h2 className="rw-heading rw-heading-secondary">New Kauf</h2>
      </header>
      <div className="rw-segment-main">
        <KaufForm onSave={onSave} loading={loading} error={error} />
      </div>
    </div>
  )
}

export default NewKauf
