#' Statistical Properties of the Modified Topp-Leone Distribution
#'
#' Functions to calculate various statistical properties of the Modified Topp-Leone (MTL)
#' distribution including mode, mean, quantiles, mean deviations, inequality measures,
#' mean residual life, mean past life, probability-weighted moments, entropies,
#' stress-strength reliability, and order statistics.
#'
#' @param alpha Shape parameter of the MTL distribution (\code{alpha > 0}).
#' @param alpha1,alpha2 Shape parameters for two independent MTL variables in stress-strength reliability.
#' @param r Order of the raw moment or probability-weighted moment.
#' @param s Parameter for probability-weighted moment.
#' @param y Evaluation point for residual life, past life, inequality curves, or order statistics.
#' @param n Sample size for order statistics.
#' @param u Index of the order statistic (\code{1 <= u <= n}).
#' @param n_terms Number of terms to use in series expansions (default: 100).
#' @param type Type of entropy (\code{"renyi"}, \code{"shannon"}, or \code{"omega"}) or order statistics output (\code{"pdf"} or \code{"cdf"}).
#' @param gamma Order parameter for Rényi or \eqn{\omega}-entropy (\code{gamma > 0, gamma != 1}).
#'
#' @return
#' Numeric scalar or vector corresponding to the calculated statistical property:
#' \itemize{
#'   \item \code{mode_mtl}: Mode of the MTL distribution.
#'   \item \code{mean_mtl}: Mean of the MTL distribution.
#'   \item \code{moments_mtl}: $r$-th raw moment (finite for $r = 1$).
#'   \item \code{quantiles_mtl}: Named vector of quantiles, median, skewness, and kurtosis.
#'   \item \code{meandev_mtl}: Mean deviation about mean and median.
#'   \item \code{inequality_mtl}: Lorenz, Bonferroni, and Zenga inequality measures.
#'   \item \code{mrl_mtl}: Mean residual life function.
#'   \item \code{mpl_mtl}: Mean past life (expected inactivity time) function.
#'   \item \code{pwm_mtl}: Probability-weighted moment \eqn{\mu_{r,s}}.
#'   \item \code{entropy_mtl}: Specified entropy measure.
#'   \item \code{ssr_mtl}: Stress-strength reliability \eqn{R = P[Y_2 < Y_1]}.
#'   \item \code{order_stats_mtl}: Density or CDF of the $u$-th order statistic.
#' }
#'
#' @references
#' Singh, B., Tyagi, S., Singh, R. P., and Tyagi, A. (2025). Modified Topp-Leone
#' Distribution: Properties, Classical and Bayesian Estimation with Application to COVID-19
#' and Reliability Data. \emph{Thailand Statistician}, 23(1), 72-96.
#'
#' @author Shikhar Tyagi, Abhishek Tyagi, Arvind Pandey, Bhupendra Singh, Vrijesh Tripathi
#'
#' @examples
#' # Mode and Mean
#' mode_mtl(alpha = 2.5)
#' mean_mtl(alpha = 1.5)
#'
#' # Quantiles summary
#' quantiles_mtl(alpha = 1.5)
#'
#' # Mean deviations
#' meandev_mtl(alpha = 1.5)
#'
#' # Inequality measures at y = 1
#' inequality_mtl(y = 1, alpha = 1.5)
#'
#' # Mean residual life and past life
#' mrl_mtl(y = 1, alpha = 1.5)
#' mpl_mtl(y = 1, alpha = 1.5)
#'
#' # Entropies
#' entropy_mtl(alpha = 1.5, type = "shannon")
#' entropy_mtl(alpha = 1.5, type = "renyi", gamma = 0.5)
#'
#' # Stress-Strength Reliability
#' ssr_mtl(alpha1 = 2, alpha2 = 3)
#'
#' # Order statistics density for median in n = 5 sample
#' order_stats_mtl(y = 1, alpha = 1.5, n = 5, u = 3, type = "pdf")
#'
#' @name properties_mtl
#' @rdname properties_mtl
#' @export
mode_mtl <- function(alpha) {
  if (alpha <= 1) {
    return(0)
  } else {
    mode_val <- sqrt(1 + (1 / 3) * sqrt(6 * alpha + 3)) - 1
    return(mode_val)
  }
}

#' @rdname properties_mtl
#' @export
mean_mtl <- function(alpha, n_terms = 100) {
  if (alpha <= 0) stop("'alpha' must be positive.")
  
  res <- tryCatch({
    stats::integrate(function(y) y * dmtl(y, alpha), lower = 0, upper = Inf)$value
  }, error = function(e) {
    j <- 0:(n_terms - 1)
    coefs <- choose(alpha - 1, j)
    beta_vals <- beta(alpha + 1, j + 1)
    2 * alpha * sum(coefs * beta_vals)
  })
  
  return(res)
}

#' @rdname properties_mtl
#' @export
moments_mtl <- function(r, alpha, n_terms = 100) {
  if (r == 1) {
    return(mean_mtl(alpha, n_terms = n_terms))
  } else if (r >= 2) {
    warning("MTL distribution does not have finite moments of order r >= 2.")
    return(Inf)
  } else {
    stop("Order 'r' must be a positive integer.")
  }
}

#' @rdname properties_mtl
#' @export
quantiles_mtl <- function(alpha) {
  q1 <- qmtl(0.25, alpha)
  q2 <- qmtl(0.50, alpha)
  q3 <- qmtl(0.75, alpha)
  q18 <- qmtl(1 / 8, alpha)
  q38 <- qmtl(3 / 8, alpha)
  q58 <- qmtl(5 / 8, alpha)
  q78 <- qmtl(7 / 8, alpha)
  
  sk <- (q3 + q1 - 2 * q2) / (q3 - q1)
  ku <- (q78 - q58 + q38 - q18) / (q3 - q1)
  m_val <- mode_mtl(alpha)
  
  res <- c(
    Q1 = q1,
    Median = q2,
    Q3 = q3,
    Mode = m_val,
    Skewness = sk,
    Kurtosis = ku
  )
  return(res)
}

#' @rdname properties_mtl
#' @export
meandev_mtl <- function(alpha) {
  mu <- mean_mtl(alpha)
  med <- qmtl(0.5, alpha)
  
  i_mu <- stats::integrate(function(y) y * dmtl(y, alpha), lower = 0, upper = mu)$value
  i_med <- stats::integrate(function(y) y * dmtl(y, alpha), lower = 0, upper = med)$value
  
  f_mu <- pmtl(mu, alpha)
  f_med <- pmtl(med, alpha)
  
  md_mean <- 2 * (mu * f_mu - i_mu)
  md_median <- 2 * (med * f_med - i_med)
  
  return(c(MD_mean = md_mean, MD_median = md_median))
}

#' @rdname properties_mtl
#' @export
inequality_mtl <- function(y, alpha) {
  mu <- mean_mtl(alpha)
  fy <- pmtl(y, alpha)
  sy <- smtl(y, alpha)
  
  i_lower <- stats::integrate(function(z) z * dmtl(z, alpha), lower = 0, upper = y)$value
  mu_minus <- i_lower / fy
  
  i_upper <- stats::integrate(function(z) z * dmtl(z, alpha), lower = y, upper = Inf)$value
  mu_plus <- i_upper / sy
  
  lorenz <- i_lower / mu
  bonferroni <- mu_minus / mu
  zenga <- 1 - (mu_minus / mu_plus)
  
  return(c(Lorenz = lorenz, Bonferroni = bonferroni, Zenga = zenga))
}

#' @rdname properties_mtl
#' @export
mrl_mtl <- function(y, alpha) {
  sy <- smtl(y, alpha)
  if (sy <= 0) return(0)
  
  i_val <- stats::integrate(function(z) smtl(z, alpha), lower = y, upper = Inf)$value
  return(i_val / sy)
}

#' @rdname properties_mtl
#' @export
mpl_mtl <- function(y, alpha) {
  fy <- pmtl(y, alpha)
  if (fy <= 0) return(0)
  
  i_val <- stats::integrate(function(z) pmtl(z, alpha), lower = 0, upper = y)$value
  return(i_val / fy)
}

#' @rdname properties_mtl
#' @export
pwm_mtl <- function(r, s, alpha) {
  res <- stats::integrate(function(y) (y^r) * (pmtl(y, alpha)^s) * dmtl(y, alpha), lower = 0, upper = Inf)$value
  return(res)
}

#' @rdname properties_mtl
#' @export
entropy_mtl <- function(alpha, type = c("shannon", "renyi", "omega"), gamma = 0.5) {
  type <- match.arg(type)
  
  if (type == "shannon") {
    res <- -stats::integrate(function(y) dmtl(y, alpha) * dmtl(y, alpha, log = TRUE), lower = 0, upper = Inf)$value
    return(res)
  } else if (type == "renyi") {
    if (gamma <= 0 || gamma == 1) stop("'gamma' must be positive and != 1 for Renyi entropy.")
    integral_val <- stats::integrate(function(y) dmtl(y, alpha)^gamma, lower = 0, upper = Inf)$value
    res <- (1 / (1 - gamma)) * log(integral_val)
    return(res)
  } else if (type == "omega") {
    if (gamma <= 0 || gamma == 1) stop("'gamma' must be positive and != 1 for omega entropy.")
    integral_val <- stats::integrate(function(y) dmtl(y, alpha)^gamma, lower = 0, upper = Inf)$value
    # Tsallis / Omega entropy definition: H_omega(Y) = (1 / (gamma - 1)) * (1 - integral_val)
    res <- (1 / (1 - gamma)) * (integral_val - 1)
    return(res)
  }
}

#' @rdname properties_mtl
#' @export
ssr_mtl <- function(alpha1, alpha2) {
  if (alpha1 <= 0 || alpha2 <= 0) stop("Shape parameters 'alpha1' and 'alpha2' must be positive.")
  return(alpha1 / (alpha1 + alpha2))
}

#' @rdname properties_mtl
#' @export
order_stats_mtl <- function(y, alpha, n, u, type = c("pdf", "cdf")) {
  type <- match.arg(type)
  if (u < 1 || u > n) stop("'u' must be between 1 and 'n'.")
  
  fy <- dmtl(y, alpha)
  Fy <- pmtl(y, alpha)
  Sy <- 1 - Fy
  
  if (type == "pdf") {
    c_factor <- factorial(n) / (factorial(u - 1) * factorial(n - u))
    res <- c_factor * fy * (Fy^(u - 1)) * (Sy^(n - u))
    return(res)
  } else {
    res <- stats::pbeta(Fy, u, n - u + 1)
    return(res)
  }
}
