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

import 'src/lib/formatters'

const DELETE_KATEGORIE_MUTATION = gql`
  mutation DeleteKategorieMutation($id: Int!) {
    deleteKategorie(id: $id) {
      id
    }
  }
`

const Kategorie = ({ kategorie }) => {
  const [deleteKategorie] = useMutation(DELETE_KATEGORIE_MUTATION, {
    onCompleted: () => {
      toast.success('Kategorie deleted')
      navigate(routes.kategories())
    },
    onError: (error) => {
      toast.error(error.message)
    },
  })

  const onDeleteClick = (id) => {
    if (confirm('Are you sure you want to delete kategorie ' + id + '?')) {
      deleteKategorie({ variables: { id } })
    }
  }

  return (
    <>
      <div className="rw-segment">
        <header className="rw-segment-header">
          <h2 className="rw-heading rw-heading-secondary">
            Kategorie {kategorie.id} Detail
          </h2>
        </header>
        <table className="rw-table">
          <tbody>
            <tr>
              <th>Id</th>
              <td>{kategorie.id}</td>
            </tr>
            <tr>
              <th>Name</th>
              <td>{kategorie.name}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <nav className="rw-button-group">
        <Link
          to={routes.editKategorie({ id: kategorie.id })}
          className="rw-button rw-button-blue"
        >
          Edit
        </Link>
        <button
          type="button"
          className="rw-button rw-button-red"
          onClick={() => onDeleteClick(kategorie.id)}
        >
          Delete
        </button>
      </nav>
    </>
  )
}

export default Kategorie
