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

import { timeTag } from 'src/lib/formatters'

const DELETE_KAUF_MUTATION = gql`
  mutation DeleteKaufMutation($id: Int!) {
    deleteKauf(id: $id) {
      id
    }
  }
`

const Kauf = ({ kauf }) => {
  const [deleteKauf] = useMutation(DELETE_KAUF_MUTATION, {
    onCompleted: () => {
      toast.success('Kauf deleted')
      navigate(routes.kaufs())
    },
    onError: (error) => {
      toast.error(error.message)
    },
  })

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

  return (
    <>
      <div className="rw-segment">
        <header className="rw-segment-header">
          <h2 className="rw-heading rw-heading-secondary">
            Kauf {kauf.id} Detail
          </h2>
        </header>
        <table className="rw-table">
          <tbody>
            <tr>
              <th>Id</th>
              <td>{kauf.id}</td>
            </tr>
            <tr>
              <th>Timestamp</th>
              <td>{timeTag(kauf.timestamp)}</td>
            </tr>
            <tr>
              <th>Preis ges</th>
              <td>{kauf.preis_ges}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <nav className="rw-button-group">
        <Link
          to={routes.editKauf({ id: kauf.id })}
          className="rw-button rw-button-blue"
        >
          Edit
        </Link>
        <button
          type="button"
          className="rw-button rw-button-red"
          onClick={() => onDeleteClick(kauf.id)}
        >
          Delete
        </button>
      </nav>
    </>
  )
}

export default Kauf
