#' @title SEQIC Indicator 6 - Delayed Arrival Following Low GCS
#'
#' @description
#'
#' `r lifecycle::badge("experimental")`
#'
#' Computes SEQIC Indicator 6 for trauma system quality monitoring. This
#' indicator measures the proportion of patients presenting with a Glasgow Coma
#' Scale (GCS) score < 9 who arrive at a trauma level I–IV center more than 180
#' minutes after injury. It excludes patients transferred out of the facility
#' and focuses on those transferred into a facility.
#'
#' @inheritParams seqic_indicator_1
#' @param transfer_out_indicator Column name indicating whether the patient was
#'   transferred out of the initial trauma center to definitive care. Logical,
#'   character, or factor type. Values representing "No" (e.g., FALSE, "No")
#'   indicate no transfer out.
#' @param receiving_indicator Column name indicating whether the
#'   patient was transferred into the trauma center. Logical, character, or
#'   factor type. Values representing "Yes" (e.g., TRUE, "Yes") indicate
#'   transfer in.
#' @param low_GCS_indicator Column name for identifying patients with a
#'   Glasgow Coma Scale score less than 9. Logical, character, or factor type.
#' @param time_from_injury_to_arrival Column name representing the time
#'   in minutes from injury occurrence to arrival at the trauma center. Numeric
#'   type.
#' @inheritDotParams nemsqar::nemsqa_binomial_confint conf.level correct
#'
#' @details This function:
#' \itemize{
#'   \item Filters to trauma center records from facilities at trauma levels
#'   I–IV.
#'   \item Deduplicates records using `unique_incident_id`.
#'   \item Calculates:
#'     \itemize{
#'       \item {Numerator:} Patients with low GCS (< 9) who arrived more than
#'         180 minutes after injury, were transferred in, and not transferred
#'         out.
#'       \item {Denominator:} All patients with low GCS (< 9) who were
#'         transferred in and not transferred out.
#'     }
#'   \item Optionally calculates Wilson or Clopper-Pearson confidence intervals
#'     for the resulting proportion if `calculate_ci` is specified.
#' }
#'
#' @note
#'
#' Users must ensure input columns are appropriately coded and standardized.
#' Transfer and GCS indicators should use consistent logical or textual
#' representations.
#'
#' @return A tibble summarizing SEQIC Indicator 6 results. Includes numerator,
#'   denominator, calculated proportion, and optionally 95% confidence
#'   intervals.
#'
#' @examples
#' # Packages
#' library(dplyr)
#' library(traumar)
#'
#' # Create test data for Indicator 6
#' test_data <- tibble::tibble(
#'   id = as.character(1:10),
#'   trauma_level = rep(c("I", "II", "III", "IV", "V"), times = 2),
#'   transfer_out = c("No", "No", "Yes", "No", "No", "No", "No", "No", "No",
#'   "No"),
#'   transfer_in = c("Yes", "Yes", "No", "Yes", "No", "Yes", "Yes", "Yes",
#'   "Yes", "Yes"),
#'   gcs_low = c(TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE),
#'   time_to_arrival = c(200, 100, 300, 190, 400, 181, 100, 179, 240, 178)
#' )
#'
#' # Run the indicator function
#' traumar::seqic_indicator_6(
#'   data = test_data,
#'   level = trauma_level,
#'   unique_incident_id = id,
#'   transfer_out_indicator = transfer_out,
#'   receiving_indicator = transfer_in,
#'   low_GCS_indicator = gcs_low,
#'   time_from_injury_to_arrival = time_to_arrival
#' )
#'
#' @author Nicolas Foss, Ed.D., MS
#'
#' @export
#'
seqic_indicator_6 <- function(
  data,
  level,
  included_levels = c("I", "II", "III", "IV"),
  unique_incident_id,
  transfer_out_indicator,
  receiving_indicator,
  low_GCS_indicator,
  time_from_injury_to_arrival,
  groups = NULL,
  calculate_ci = NULL,
  ...
) {
  ###___________________________________________________________________________
  ### Data validation ----
  ###___________________________________________________________________________

  # Validate if `data` is a data frame or tibble. ----
  validate_data_structure(
    input = data,
    structure_type = c("data.frame", "tbl", "tbl_df"),
    type = "error"
  )

  # make the `level` column accessible for validation ----
  level_check <- validate_data_pull(
    input = data,
    type = "error",
    col = {{ level }},
    var_name = "level"
  )

  # validate `level` ----
  validate_character_factor(
    input = level_check,
    type = "error",
    var_name = "level"
  )

  # make the `unique_incident_id` column accessible for validation ----
  unique_incident_id_check <- validate_data_pull(
    input = data,
    type = "error",
    col = {{ unique_incident_id }},
    var_name = "unique_incident_id"
  )

  # Validate `unique_incident_id` ----
  validate_class(
    input = unique_incident_id_check,
    class_type = c("numeric", "integer", "character", "factor"),
    logic = "or",
    type = "error",
    var_name = "unique_incident_id"
  )

  # Ensure that `transfer_out_indicator` can be validated  ----
  transfer_out_indicator_check <- validate_data_pull(
    input = data,
    col = {{ transfer_out_indicator }},
    type = "error",
    var_name = "transfer_out_indicator"
  )

  # Validate `transfer_out_indicator` ----
  validate_class(
    input = transfer_out_indicator_check,
    class_type = c("logical", "character", "factor"),
    logic = "or",
    type = "error",
    var_name = "transfer_out_indicator"
  )

  # Ensure that `receiving_indicator` can be validated
  receiving_indicator_check <- validate_data_pull(
    input = data,
    col = {{ receiving_indicator }},
    type = "error",
    var_name = "receiving_indicator"
  )

  # Validate that `receiving_indicator` is character, factor, or logical. ----
  validate_class(
    input = receiving_indicator_check,
    class_type = c("logical", "character", "factor"),
    logic = "or",
    type = "error",
    var_name = "receiving_indicator"
  )

  # Ensure that `low_GCS_indicator` can be validated ----
  low_GCS_indicator_check <- validate_data_pull(
    input = data,
    col = {{ low_GCS_indicator }},
    type = "error",
    var_name = "low_GCS_indicator"
  )

  # Validate that `low_GCS_indicator` is character, factor, or logical ----
  validate_class(
    input = low_GCS_indicator_check,
    class_type = c("logical", "character", "factor"),
    logic = "or",
    type = "error",
    var_name = "low_GCS_indicator"
  )

  # Ensure that `time_from_injury_to_arrival` can be validated
  time_from_injury_to_arrival_check <- validate_data_pull(
    input = data,
    col = {{ time_from_injury_to_arrival }},
    type = "error",
    var_name = "time_from_injury_to_arrival"
  )

  # Validate that `time_from_injury_to_arrival` is numeric.
  validate_numeric(
    input = time_from_injury_to_arrival_check,
    type = "error",
    var_name = "time_from_injury_to_arrival"
  )

  # Check if all elements in groups are strings (i.e., character vectors) ----
  validate_character_factor(input = groups, type = "error", null_ok = TRUE)

  # Check if all `groups` exist in the `data`.
  validate_names(
    input = data,
    check_names = groups,
    type = "error",
    var_name = "groups",
    null_ok = TRUE
  )

  # Validate the `calculate_ci` argument ----
  calculate_ci <- validate_choice(
    input = calculate_ci,
    choices = c("wilson", "clopper-pearson"),
    several.ok = FALSE,
    type = "error",
    null_ok = TRUE,
    var_name = "calculate_ci"
  )

  # Validate the `included_levels` argument ----
  validate_class(
    input = included_levels,
    class_type = c("numeric", "character", "factor", "integer"),
    type = "error",
    logic = "or"
  )

  ###___________________________________________________________________________
  ### Calculations ----
  ###___________________________________________________________________________

  # Filter for trauma levels I-IV, deduplicate by `unique_incident_id` ----
  # then summarize.
  seqic_6 <- data |>
    dplyr::filter({{ level }} %in% included_levels) |>
    dplyr::distinct({{ unique_incident_id }}, .keep_all = TRUE) |>
    dplyr::summarize(
      numerator_6 = sum(
        {{ low_GCS_indicator }} == TRUE & # GCS < 9
          {{ time_from_injury_to_arrival }} > 180 & # Time to arrival > 180 min
          {{ receiving_indicator }} %in% c(TRUE, "Yes") & # Hospital received
          {{ transfer_out_indicator }} %in% c(FALSE, "No"), # No transfer out
        na.rm = TRUE
      ),
      denominator_6 = sum(
        {{ low_GCS_indicator }} == TRUE &
          {{ receiving_indicator }} %in% c(TRUE, "Yes") &
          {{ transfer_out_indicator }} %in% c(FALSE, "No"),
        na.rm = TRUE
      ),
      seqic_6 = dplyr::if_else(
        denominator_6 > 0,
        numerator_6 / denominator_6,
        NA_real_
      ),
      .by = {{ groups }} # Grouping if applicable
    )

  # Optional: Add binomial confidence intervals if requested. ----
  if (!is.null(calculate_ci)) {
    seqic_6 <- seqic_6 |>
      dplyr::bind_cols(
        nemsqar::nemsqa_binomial_confint(
          data = seqic_6,
          x = numerator_6, # Number of positive outcomes.
          n = denominator_6, # Number of eligible patients.
          method = calculate_ci,
          ...
        ) |>
          dplyr::select(lower_ci, upper_ci) |> # Drop intermediate columns.
          dplyr::rename(lower_ci_6 = lower_ci, upper_ci_6 = upper_ci) # Rename CIs for clarity.
      )
  }

  # Add a `Data` label if not grouped ----
  # or arrange output by grouping variables.
  if (is.null(groups)) {
    seqic_6 <- seqic_6 |>
      tibble::add_column(data = "population/sample", .before = "numerator_6")
  } else if (!is.null(groups)) {
    seqic_6 <- seqic_6 |>
      dplyr::arrange(!!!rlang::syms(groups)) # Order rows based on group vars.
  }

  # Return the final summarized dataset. ----
  return(seqic_6)
}
