# Chapter 7 - Interactive tables with {DT}: raw vs. formatted
library(shiny)
library(bslib)
library(dplyr)
library(DT)
library(gapminder)

continents <- levels(gapminder$continent)

ui <- page_sidebar(
  title = "Interactive tables with {DT}",
  sidebar = sidebar(
    sliderInput("year", "Year", min = 1952, max = 2007, value = 2007, step = 5, sep = ""),
    checkboxGroupInput("continents", "Continents", choices = continents, selected = continents)
  ),
  layout_columns(
    col_widths = c(6, 6),
    card(card_header(code("datatable(filtered())"), ": the default"), DTOutput("raw")),
    card(card_header(code("datatable(...) |> format*()"), ": formatted"), DTOutput("table"))
  )
)

server <- function(input, output, session) {
  filtered <- reactive({
    validate(need(length(input$continents) > 0, "Select at least one continent."))
    gapminder |>
      filter(year == input$year, continent %in% input$continents)
  })

  # Default table: row names, raw column names, raw numbers
  output$raw <- renderDT(datatable(filtered(), options = list(pageLength = 8, scrollX = TRUE)))

  # Formatted table (code of the slide)
  output$table <- renderDT({
    filtered() |>
      transmute(country, continent, lifeExp, pop_m = pop / 1e6, gdpPercap) |>
      arrange(desc(lifeExp)) |>
      datatable(
        rownames = FALSE,
        colnames = c("Country", "Continent", "Life exp.", "Pop. (M)", "GDP/cap."),
        options = list(pageLength = 8)
      ) |>
      formatRound(c("lifeExp", "pop_m"), digits = 1) |>
      formatCurrency("gdpPercap", digits = 0)
  })
}

shinyApp(ui, server)
