#' Plot predicted versus observed counts
#'
#' @param pred.df A data frame containing the predicted counts, as generated by
#' `predict_counts()`
#' @param data Data list (from `prepare_data()`)
#' @param byplant Logical. If TRUE, show predicted and observed counts per plant
#' (using `ggplot2::facet_wrap()`). If FALSE, show all interactions in the same plot.
#' @param width width of the credible interval (default = 0.95).
#' @param ... Further arguments to be passed to `ggplot2::facet_wrap()` if
#' `byplant = TRUE`, or to `tidybayes::geom_pointinterval()` if `byplant = FALSE`.
#'
#' @return A ggplot object
#' @export
#'
#' @examplesIf interactive()
#' data(web)
#' dt <- prepare_data(mat = web, sampl.eff = rep(20, nrow(web)))
#' fit <- fit_model(dt, refresh = 0)
#' pred.df <- predict_counts(fit, dt)
#' plot_counts_pred_obs(pred.df, dt)
#' plot_counts_pred_obs(pred.df, dt, fatten_point = 3)
#' plot_counts_pred_obs(pred.df, dt, byplant = TRUE)
#' plot_counts_pred_obs(pred.df, dt, byplant = TRUE, scale = "free")

plot_counts_pred_obs <- function(pred.df = NULL, data = NULL, byplant = FALSE, width = 0.95, ...) {

  obs <- data$M |>
    network.tools::wide2long(int.name = "Count.obs")

  pred <- pred.df |>
    dplyr::select(Plant, Animal, Count.pred = count) |>
    tidybayes::mean_qi(.width = width) |>
    dplyr::left_join(obs, by = c("Plant", "Animal"))

  gg <- ggplot2::ggplot(pred) +
    ggplot2::geom_abline(intercept = 0, slope = 1, lty = 2) +
    ggplot2::labs(x = "Observed counts", y = "Predicted counts")

  if (isTRUE(byplant)) {
    gg <- gg +
      tidybayes::geom_pointinterval(ggplot2::aes(x = Count.obs, y = Count.pred,
                                        ymin = .lower, ymax = .upper)) +
      ggplot2::facet_wrap(~Plant, ...)
  } else {
    gg <- gg +
      tidybayes::geom_pointinterval(ggplot2::aes(x = Count.obs, y = Count.pred,
                                        ymin = .lower, ymax = .upper),
                                    ...)
  }

  return(gg)


}
