# Part 6: worked clinical project using the Mayo Clinic PBC data.
# Run with r/lesson-01 as your working directory (or place this file beside data/).
# Install once: install.packages(c("gtsummary", "gt", "ggplot2", "svglite"))
# Input: data/pbc_baseline.csv. Outputs: output/pbc_*.
# Source: survival::pbc 3.8-6; data/pbc_README.md documents the preparation.
# Dickson et al. (1989), https://doi.org/10.1002/hep.1840100102
# These are descriptive baseline teaching outputs from 312 randomized patients.
# The figures do not estimate treatment response or survival.
# Code follows the setup and worked solutions in 06-now-you-try.qmd.

project_packages <- c("gtsummary", "gt", "ggplot2", "svglite")
missing_packages <- project_packages[
  !vapply(project_packages, requireNamespace, logical(1), quietly = TRUE)
]
if (length(missing_packages)) {
  stop("Install these packages, then rerun: ",
       paste(missing_packages, collapse = ", "), call. = FALSE)
}

library(gtsummary)
library(ggplot2)

pbc <- read.csv("data/pbc_baseline.csv", na.strings = c("", "NA"))
pbc$treatment <- factor(pbc$treatment,
                        levels = c("D-penicillamine", "Placebo"))
pbc$sex <- factor(pbc$sex, levels = c("Female", "Male"))
pbc$stage <- factor(pbc$stage, levels = 1:4,
                    labels = c("I", "II", "III", "IV"))

str(pbc)

nrow(pbc)
anyDuplicated(pbc$patient_id)
table(pbc$treatment, useNA = "ifany")
colSums(is.na(pbc))

tbl <- tbl_summary(
  pbc,
  by = treatment,
  include = c(age, sex, bilirubin, albumin, cholesterol, stage),
  type = list(sex ~ "categorical", stage ~ "categorical"),
  label = list(
    age ~ "Age, years",
    sex ~ "Recorded sex",
    bilirubin ~ "Serum bilirubin, mg/dL",
    albumin ~ "Serum albumin, g/dL",
    cholesterol ~ "Serum cholesterol, mg/dL",
    stage ~ "Histologic stage"
  ),
  statistic = list(
    all_continuous() ~ "{median} ({p25}, {p75})",
    all_categorical() ~ "{n} ({p}%)"
  ),
  digits = list(all_continuous() ~ 1),
  percent = "column",
  missing = "ifany",
  missing_text = "Missing",
  missing_stat = "{N_miss}"
) |>
  add_overall() |>
  add_n(col_label = "**Available N**") |>
  bold_labels() |>
  modify_header(label ~ "**Characteristic**")

table_gt <- as_gt(tbl) |>
  gt::tab_header(
    title = "Table 1. Mayo Clinic PBC trial participants",
    subtitle = "Baseline characteristics by randomized treatment"
  ) |>
  gt::opt_row_striping() |>
  gt::tab_options(table.font.size = gt::px(13), heading.align = "left") |>
  gt::tab_source_note(
    "Median (Q1, Q3) or n (%). Percentages use non-missing values within each column."
  ) |>
  gt::tab_source_note(
    "Source: survival::pbc; Dickson et al. (1989). Teaching analysis of 312 randomized patients."
  )

table_gt

bilirubin_data <- pbc[!is.na(pbc$bilirubin), ]

bilirubin_hist <- ggplot(bilirubin_data, aes(x = bilirubin)) +
  geom_histogram(binwidth = 1, boundary = 0,
                 fill = "#17324D", colour = "white") +
  labs(
    title = "Baseline serum bilirubin",
    subtitle = "Mayo Clinic PBC trial | Bin width: 1 mg/dL",
    x = "Serum bilirubin (mg/dL)", y = "Number of patients",
    caption = paste0(
      "Source: survival::pbc; Dickson et al. (1989). Teaching analysis.\n",
      "Available bilirubin: n = ", nrow(bilirubin_data),
      "; missing: ", sum(is.na(pbc$bilirubin)), "."
    )
  ) +
  theme_classic(base_size = 12) +
  theme(plot.caption = element_text(hjust = 0))

bilirubin_hist

stage_data <- pbc[!is.na(pbc$stage) & !is.na(pbc$treatment), ]
stage_n <- table(stage_data$treatment)
stage_labels <- setNames(
  paste0(names(stage_n), "\n(n = ", as.integer(stage_n), ")"),
  names(stage_n)
)

stage_plot <- ggplot(stage_data, aes(x = treatment, fill = stage)) +
  geom_bar(position = "fill", width = 0.65, colour = "white") +
  scale_fill_manual(values = c(
    "I" = "#E1ECEB", "II" = "#A2C6C2",
    "III" = "#507E89", "IV" = "#17324D"
  ), drop = FALSE) +
  scale_x_discrete(labels = stage_labels) +
  scale_y_continuous(
    labels = function(x) paste0(round(100 * x), "%"),
    breaks = seq(0, 1, 0.25),
    expand = expansion(mult = c(0, 0.02))
  ) +
  labs(
    title = "Histologic stage at study entry",
    subtitle = "Mayo Clinic PBC trial | Baseline measurements",
    x = NULL, y = "Patients with recorded stage (%)", fill = "Stage",
    caption = paste0(
      "Source: survival::pbc; Dickson et al. (1989). Teaching analysis.\n",
      "Within-arm percentages; ", nrow(pbc) - nrow(stage_data),
      " patients excluded for missing stage or treatment."
    )
  ) +
  theme_classic(base_size = 12) +
  theme(legend.position = "bottom", plot.caption = element_text(hjust = 0))

stage_plot

dir.create("output", showWarnings = FALSE)
writeLines(gt::as_rtf(table_gt), "output/pbc_table1.rtf")
writeLines(gt::as_raw_html(table_gt), "output/pbc_table1.html")

plots <- list(pbc_bilirubin = bilirubin_hist, pbc_stage = stage_plot)
for (name in names(plots)) {
  ggsave(
    paste0("output/", name, ".png"), plot = plots[[name]],
    device = grDevices::png, width = 7, height = 5, units = "in",
    dpi = 300, bg = "white"
  )
  ggsave(
    paste0("output/", name, ".svg"), plot = plots[[name]],
    device = svglite::svglite, width = 7, height = 5, units = "in",
    bg = "white"
  )
}

list.files("output", pattern = "^pbc_")

message("Saved PBC teaching outputs in output/.")
