library(shinysense)
library(htmlwidgets)
library(shiny)
library(dplyr)
library(shinyjs)

# ---- APP PARAMETERS ----
APP_TITLE <- "App Title"
HELP_TEXT <- "Some guidance text can go here"

questions <- readxl::read_xlsx(here::here("docs/questions.xlsx")) %>%
  arrange(order)

question_itergen <- function(questions) {
  force(questions)
  i <- 0L
  ids <- arrange(questions, order) %>% pull(id)
  function() {
    i <<- i + 1
    if (i > length(ids)) return(NULL)
    list(
      id = ids[[i]],
      question = filter(questions, id == ids[[i]])
    )
  }
}

next_question <- question_itergen(questions)

phone_container <- function(...) {
  div(
    class = "phone-container",
    div(
      class = "marvel-device iphone8plus black",
      div(class = "top-bar"),
      div(class = "sleep"),
      div(class = "volume"),
      div(class = "camera"),
      div(class = "sensor"),
      div(class = "speaker"),
      div(class = "screen", ...),
      div(class = "home"),
      div(class = "bottom-bar")
    )
  )
}

ui <- fixedPage(
  includeCSS("devices.min.css"),
  includeCSS("t4c.css"),
  includeCSS("animate.css"),
  shinyjs::useShinyjs(),
  tags$link(rel = "stylesheet", type = "text/css", href = "https://fonts.googleapis.com/css?family=IBM+Plex+Sans:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i"),
  tags$link(rel = "stylesheet", type = "text/css", href = "https://fonts.googleapis.com/css?family=Amatic+SC:400,700|Coming+Soon"),

  # h1("A Good Name and Logo"),
  # p("This is a simple demo app..."),
  # hr(),
  p(),
  phone_container(
    div(
      class = "overlay splash animated", id = "splash-overlay",
      div(
        class = "splash-body",
        h1("Welcome!"),
        p("Talking about cancer treatment options is hard, but we're here to help."),
        actionButton("splash_next_screen", "Get Started", class = "btn-bottom-right btn-primary")
      )
    ),
    div(
        id = "app-main",
        class = "app-main animated",
        h1(APP_TITLE, class = "app-title"),
        p(HELP_TEXT, class = "help-text"),
        shinyswiprUI(
            "card_swipe_ui",
            div(class = "swiperCard-header",
                h4(class = "card-title",
                   textOutput("question_category")
                )
            ),
            div(class = "swiperCard-body",
                # h4("Question title"),
                h4(textOutput("question_topic")),
                p(textOutput("question_text"))
            )
        ),
        div(
            class = "bottom-help",
            div(class = "bottom-help-left", img(src = "/images/swipe-left.svg", width = "50px"), p("Bad")),
            div(class = "bottom-help-right", img(src = "/images/swipe-right.svg", width = "50px"), p("Okay")),
            div(class = "bottom-help-middle", span("Swipe Card", class = "bottom-help-middle-text"))
        )
    )
  ),
  hr(),
  actionButton("toggle_splash", "Toggle Splash"),
  h4("Answer History"),
  dataTableOutput("results_table")
)


server <- function(input, output, session) {
  app_data <- reactiveValues(
    init = 1L,
    iter = 1L,
    results = data_frame(question_id = integer(), swipe = character()),
    complete = FALSE,
    splash = TRUE
  )

  question <- reactive({
    if (app_data$iter > length(question_ids)) return(NULL)
    questions %>%
      filter(id == question_ids[[app_data$iter]])
  })

  card_swipe <- callModule(shinyswipr, "card_swipe_ui")

  question_ids <- arrange(questions, order) %>% pull(id)

  output$question_text <- renderText({
    if (!app_data$complete) {
      question()$`Question Text`
    } else {
      "No more questions at this time. Hang on while we crunch the numbers..."
    }
  })
  output$question_category <- renderText({
      if (!app_data$complete) question()$Category else "Thank You!"
  })
  output$question_topic <- renderText({
      if (!app_data$complete) question()$Topic else "All Done!"
  })
  output$results_table <- renderDataTable({
    app_data$results
  })


  observe({
    cat("iter:", app_data$iter, "\n")
    cat("ques:", question()$`Question Text`, "\n")
    print(app_data$results)
  })

  # on swipe
  observeEvent(card_swipe(), {
    if (app_data$complete) {
      cat("\nNothing to do.")
      return()
    }
    # save swipe event
    app_data$results <- bind_rows(
      data_frame(
        question_id = question()$id,
        swipe = card_swipe()
      ),
      app_data$results
    )

    # update app_data
    app_data$iter <- app_data$iter + 1L
    next_q <- question()
    if (is.null(next_q)) app_data$complete <- TRUE
  })

  observeEvent(input$splash_next_screen, {
    if (app_data$splash) app_data$splash <- FALSE
  })

  observeEvent(input$toggle_splash, {
      app_data$splash <- !app_data$splash
  })

  observeEvent(app_data$splash, {
    if (app_data$init) {
      app_data$init <- app_data$init - 1L
      return()
    }
    if (!app_data$splash) {
          # cli::cat_line(strftime(Sys.time(), "%F %T"), " splash out")
          shinyjs::removeClass("splash-overlay", "slideInLeft")
          shinyjs::removeClass("app-main", "slideOutRight")
          shinyjs::addClass("app-main", "slideInRight")
          shinyjs::addClass("splash-overlay", "slideOutLeft")
      } else {
          # cli::cat_line(strftime(Sys.time(), "%F %T"), " splash in")
          shinyjs::removeClass("splash-overlay", "slideOutLeft")
          shinyjs::removeClass("app-main", "slideInRight")
          shinyjs::addClass("app-main", "slideOutRight")
          shinyjs::addClass("splash-overlay", "slideInLeft")
      }
  }, priority = -100)
}

shinyApp(ui = ui, server = server)
