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

import KategorieForm from 'src/components/Kategorie/KategorieForm'

const CREATE_KATEGORIE_MUTATION = gql`
  mutation CreateKategorieMutation($input: CreateKategorieInput!) {
    createKategorie(input: $input) {
      id
    }
  }
`

const NewKategorie = () => {
  const [createKategorie, { loading, error }] = useMutation(
    CREATE_KATEGORIE_MUTATION,
    {
      onCompleted: () => {
        toast.success('Kategorie created')
        navigate(routes.kategories())
      },
      onError: (error) => {
        toast.error(error.message)
      },
    }
  )

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

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

export default NewKategorie
