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

import { useMutation } from '@redwoodjs/web'
import { toast } from '@redwoodjs/web/toast'

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

export const QUERY = gql`
  query EditKategorieById($id: Int!) {
    kategorie: kategorie(id: $id) {
      id
      name
    }
  }
`
const UPDATE_KATEGORIE_MUTATION = gql`
  mutation UpdateKategorieMutation($id: Int!, $input: UpdateKategorieInput!) {
    updateKategorie(id: $id, input: $input) {
      id
      name
    }
  }
`

export const Loading = () => <div>Loading...</div>

export const Failure = ({ error }) => (
  <div className="rw-cell-error">{error?.message}</div>
)

export const Success = ({ kategorie }) => {
  const [updateKategorie, { loading, error }] = useMutation(
    UPDATE_KATEGORIE_MUTATION,
    {
      onCompleted: () => {
        toast.success('Kategorie updated')
        navigate(routes.kategories())
      },
      onError: (error) => {
        toast.error(error.message)
      },
    }
  )

  const onSave = (input, id) => {
    updateKategorie({ variables: { id, input } })
  }

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