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

import ArtikelForm from 'src/components/Artikel/ArtikelForm'

const CREATE_ARTIKEL_MUTATION = gql`
  mutation CreateArtikelMutation($input: CreateArtikelInput!) {
    createArtikel(input: $input) {
      id
    }
  }
`

const NewArtikel = ({kategories}) => {
  const [createArtikel, { loading, error }] = useMutation(
    CREATE_ARTIKEL_MUTATION,
    {
      onCompleted: () => {
        toast.success('Artikel created')
        navigate(routes.artikels())
      },
      onError: (error) => {
        toast.error(error.message)
      },
    }
  )

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

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

export default NewArtikel
