# Chapter 9 - Step 3: a small dashboard (KPIs, graph, table, CSV download)
library(shiny)
library(bslib)
library(bsicons)
library(dplyr)
library(ggplot2)
library(DT)
library(gapminder)

continents <- levels(gapminder$continent)

# Number formatters (from {scales}), e.g. 6.3B, $6,124
fmt_big    <- scales::label_number(scale_cut = scales::cut_short_scale(), accuracy = 0.1)
fmt_dollar <- scales::label_dollar(accuracy = 1)

ui <- page_sidebar(
  title = "Gapminder dashboard",
  sidebar = sidebar(
    sliderInput(
      inputId = "year", label = "Year",
      min = 1952, max = 2007, value = 2007, step = 5, sep = ""
    ),
    checkboxGroupInput(
      inputId = "continents", label = "Continents",
      choices = continents, selected = continents
    ),
    downloadButton(outputId = "download_csv", label = "Download data (CSV)")
  ),
  # Row 1: KPIs
  layout_columns(
    fill = FALSE,
    value_box(
      title = "Countries", value = textOutput("kpi_n"),
      showcase = bs_icon("globe2"), theme = "primary"
    ),
    value_box(
      title = "Total population", value = textOutput("kpi_pop"),
      showcase = bs_icon("people-fill"), theme = "secondary"
    ),
    value_box(
      title = "Median life expectancy", value = textOutput("kpi_life"),
      showcase = bs_icon("heart-pulse"), theme = "success"
    ),
    value_box(
      title = "Median GDP per capita", value = textOutput("kpi_gdp"),
      showcase = bs_icon("cash-coin"), theme = "info"
    )
  ),
  # Row 2: graph + table
  layout_columns(
    col_widths = c(6, 6),
    card(
      full_screen = TRUE,
      card_header("Life expectancy vs. GDP per capita"),
      plotOutput("scatter")
    ),
    card(
      full_screen = TRUE,
      card_header("Countries"),
      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)
  })

  # --- KPIs ---
  output$kpi_n    <- renderText(nrow(filtered()))
  output$kpi_pop  <- renderText(fmt_big(sum(as.numeric(filtered()$pop))))
  output$kpi_life <- renderText(paste(round(median(filtered()$lifeExp), 1), "years"))
  output$kpi_gdp  <- renderText(fmt_dollar(median(filtered()$gdpPercap)))

  # --- Graph ---
  output$scatter <- renderPlot({
    filtered() |>
      ggplot(aes(x = gdpPercap, y = lifeExp, colour = continent, size = pop)) +
      geom_point(alpha = 0.6) +
      scale_x_log10(labels = scales::label_dollar(accuracy = 1)) +
      scale_colour_discrete(drop = FALSE) +
      scale_size_area(max_size = 15, guide = "none") +
      labs(x = "GDP per capita (log scale)", y = "Life expectancy (years)", colour = NULL) +
      theme_minimal(base_size = 15) +
      theme(legend.position = "bottom")
  })

  # --- Table ---
  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)
  })

  # --- CSV export of the filtered data ---
  output$download_csv <- downloadHandler(
    filename = \() paste0("gapminder_", input$year, ".csv"),
    content  = \(file) readr::write_csv(filtered(), file)
  )
}

shinyApp(ui, server)
