#' Plot DP-Quantile Bootstrap Result
#'
#' @param object Object returned by dpq_bootstrap().
#' @param dates Optional vector of dates.
#' @param interval Character. Either '50' or '95'.
#'
#' @return A ggplot object.
#'
#' @examples
#' x <- c(120, 125, 118, 130, 128, 135, 140, 138, 145, 150)
#' res <- dpq_bootstrap(x, R = 20, alpha = 1, seed = 123)
#' if (requireNamespace('ggplot2', quietly = TRUE)) {
#'   plot_dpq(res, interval = '50')
#' }
#'
#' @importFrom rlang .data
#' @export
plot_dpq <- function(object, dates = NULL, interval = '50') {

  if (!inherits(object, 'dpq_bootstrap')) {
    stop('object must be a result returned by dpq_bootstrap().')
  }

  if (!requireNamespace('ggplot2', quietly = TRUE)) {
    stop('The ggplot2 package is required.')
  }

  n <- length(object$original)

  if (is.null(dates)) {
    dates <- 1:n
  }

  if (length(dates) != n) {
    stop('dates must have the same length as the original series.')
  }

  if (interval == '50') {
    low <- object$q25
    high <- object$q75
    title_interval <- 'Interval 25%-75%'
  } else if (interval == '95') {
    low <- object$q025
    high <- object$q975
    title_interval <- 'Interval 2.5%-97.5%'
  } else {
    stop('interval must be 50 or 95.')
  }

  df <- data.frame(
    Date = dates,
    Original = object$original,
    Bootstrap_mean = object$mean_series,
    Low = low,
    High = high
  )

  ggplot2::ggplot(df, ggplot2::aes(x = .data[['Date']])) +
    ggplot2::geom_ribbon(
      ggplot2::aes(ymin = .data[['Low']], ymax = .data[['High']]),
      fill = 'grey80',
      alpha = 0.6
    ) +
    ggplot2::geom_line(
      ggplot2::aes(y = .data[['Original']], color = 'Original series'),
      linewidth = 1
    ) +
    ggplot2::geom_point(
      ggplot2::aes(y = .data[['Original']], color = 'Original series'),
      size = 1.5
    ) +
    ggplot2::geom_line(
      ggplot2::aes(y = .data[['Bootstrap_mean']], color = 'Bootstrap mean'),
      linewidth = 1
    ) +
    ggplot2::labs(
      title = paste('DP-Quantile Bootstrap -', title_interval),
      x = 'Time',
      y = 'Value',
      color = ''
    ) +
    ggplot2::theme_minimal()
}
