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

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

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

export const QUERY = gql`
  query EditKaufById($id: Int!) {
    kauf: kauf(id: $id) {
      id
      timestamp
      preis_ges
    }
  }
`
const UPDATE_KAUF_MUTATION = gql`
  mutation UpdateKaufMutation($id: Int!, $input: UpdateKaufInput!) {
    updateKauf(id: $id, input: $input) {
      id
      timestamp
      preis_ges
    }
  }
`

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

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

export const Success = ({ kauf }) => {
  const [updateKauf, { loading, error }] = useMutation(UPDATE_KAUF_MUTATION, {
    onCompleted: () => {
      toast.success('Kauf updated')
      navigate(routes.kaufs())
    },
    onError: (error) => {
      toast.error(error.message)
    },
  })

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

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