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

import { QUERY } from 'src/components/Artikel/ArtikelsCell'
import { truncate } from 'src/lib/formatters'

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

const ArtikelsList = ({ artikels }) => {
  const [deleteArtikel] = useMutation(DELETE_ARTIKEL_MUTATION, {
    onCompleted: () => {
      toast.success('Artikel deleted')
    },
    onError: (error) => {
      toast.error(error.message)
    },
    // This refetches the query on the list page. Read more about other ways to
    // update the cache over here:
    // https://www.apollographql.com/docs/react/data/mutations/#making-all-other-cache-updates
    refetchQueries: [{ query: QUERY }],
    awaitRefetchQueries: true,
  })

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

  return (
    <div className="rw-segment rw-table-wrapper-responsive">
      <table className="rw-table">
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Preis</th>
            <th>Kategorie</th>
            <th>&nbsp;</th>
          </tr>
        </thead>
        <tbody>
          {artikels.map((artikel) => (
            <tr key={artikel.id}>
              <td>{truncate(artikel.id)}</td>
              <td>{truncate(artikel.name)}</td>
              <td>{truncate(artikel.preis)}</td>
              <td>{truncate(artikel.kategorie.name)}</td>
              <td>
                <nav className="rw-table-actions">
                  <Link
                    to={routes.artikel({ id: artikel.id })}
                    title={'Show artikel ' + artikel.id + ' detail'}
                    className="rw-button rw-button-small"
                  >
                    Show
                  </Link>
                  <Link
                    to={routes.editArtikel({ id: artikel.id })}
                    title={'Edit artikel ' + artikel.id}
                    className="rw-button rw-button-small rw-button-blue"
                  >
                    Edit
                  </Link>
                  <button
                    type="button"
                    title={'Delete artikel ' + artikel.id}
                    className="rw-button rw-button-small rw-button-red"
                    onClick={() => onDeleteClick(artikel.id)}
                  >
                    Delete
                  </button>
                </nav>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

export default ArtikelsList
