# Chapter 7 - A gallery of outputs: each card pairs a UI placeholder with its render function
library(shiny)
library(bslib)
library(bsicons)
library(dplyr)
library(ggplot2)
library(DT)
library(plotly)
library(gapminder)

# One card = "placeholder + render function" in the header, the output in the body
output_card <- function(ui_fun, render_fun, output_ui) {
  card(
    card_header(code(ui_fun), " + ", code(render_fun)),
    output_ui
  )
}

ui <- page_fillable(
  title = "Shiny outputs",
  tags$style("pre { white-space: pre-wrap; }"),   # wrap long printed output
  sliderInput("year", "Year (every output below depends on it)",
              min = 1952, max = 2007, value = 2007, step = 5, sep = "", width = "100%"),
  layout_column_wrap(
    width = 1 / 3, heights_equal = "row",
    output_card("textOutput()", "renderText()", textOutput("text")),
    output_card("verbatimTextOutput()", "renderPrint()", verbatimTextOutput("print")),
    output_card("value_box(textOutput())", "renderText()",
                value_box(title = "Median life expectancy", value = textOutput("kpi"),
                          showcase = bs_icon("heart-pulse"), theme = "primary")),
    output_card("tableOutput()", "renderTable()", tableOutput("table")),
    output_card("DTOutput()", "renderDT()", DTOutput("dt")),
    output_card("uiOutput()", "renderUI()", uiOutput("ui")),
    output_card("plotOutput()", "renderPlot()", plotOutput("plot", height = "220px")),
    output_card("plotlyOutput()", "renderPlotly()", plotlyOutput("plotly", height = "220px")),
    output_card("downloadButton()", "downloadHandler()",
                downloadButton("download", "Download the data (CSV)"))
  )
)

server <- function(input, output, session) {
  data_year <- reactive(filter(gapminder, year == input$year))

  output$text  <- renderText(paste(nrow(data_year()), "countries in", input$year))
  output$print <- renderPrint(quantile(data_year()$lifeExp, c(0.25, 0.5, 0.75)))
  output$kpi   <- renderText(paste(round(median(data_year()$lifeExp), 1), "years"))

  output$table <- renderTable(
    data_year() |>
      group_by(continent) |>
      summarise(countries = n(), life_exp = median(lifeExp)),
    spacing = "xs", digits = 1
  )

  output$dt <- renderDT(
    datatable(select(data_year(), country, continent, lifeExp),
              rownames = FALSE, options = list(pageLength = 3, dom = "tp"))
  )

  output$ui <- renderUI({
    best <- slice_max(data_year(), lifeExp, n = 1)
    tags$p("Highest life expectancy: ", strong(best$country),
           paste0(" (", round(best$lifeExp, 1), " years)"))
  })

  output$plot <- renderPlot(
    ggplot(data_year(), aes(x = continent, y = lifeExp)) +
      geom_boxplot(fill = "#e6f0ff") +
      labs(x = NULL, y = "Life expectancy") +
      theme_minimal(base_size = 13)
  )

  output$plotly <- renderPlotly({
    p <- ggplot(data_year(), aes(x = gdpPercap, y = lifeExp, colour = continent, text = country)) +
      geom_point() +
      scale_x_log10() +
      labs(x = "GDP per capita (log)", y = "Life expectancy") +
      theme_minimal(base_size = 11) +
      theme(legend.position = "none")
    ggplotly(p, tooltip = "text") |> config(displayModeBar = FALSE)
  })

  output$download <- downloadHandler(
    filename = \() paste0("gapminder_", input$year, ".csv"),
    content  = \(file) readr::write_csv(data_year(), file)
  )
}

shinyApp(ui, server)
