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

import 'src/lib/formatters'

const DELETE_ARTIKEL_MUTATION = gql`
  mutation DeleteArtikelMutation($id: Int!) {
    deleteArtikel(id: $id) {
      id
    }
  }
`

const Artikel = ({ artikel }) => {
  const [deleteArtikel] = useMutation(DELETE_ARTIKEL_MUTATION, {
    onCompleted: () => {
      toast.success('Artikel deleted')
      navigate(routes.artikels())
    },
    onError: (error) => {
      toast.error(error.message)
    },
  })

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

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

export default Artikel
