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

import { QUERY } from 'src/components/Kategorie/KategoriesCell'
import { truncate } from 'src/lib/formatters'

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

const KategoriesList = ({ kategories }) => {
  const [deleteKategorie] = useMutation(DELETE_KATEGORIE_MUTATION, {
    onCompleted: () => {
      toast.success('Kategorie 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 kategorie ' + id + '?')) {
      deleteKategorie({ variables: { id } })
    }
  }

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

export default KategoriesList
