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

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"),

  # 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(
        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")
                   # "Card Title",
                )
            ),
            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) {
  card_swipe <- callModule(shinyswipr, "card_swipe_ui")

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

  # Init outputs
  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
  })

  app_data <- reactiveValues(
    iter = 1L,
    results = data_frame(question_id = integer(), swipe = character()),
    complete = FALSE,
    splash = FALSE
  )

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

  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 outputs
    app_data$iter <- app_data$iter + 1L
    next_q <- question()
    if (!is.null(next_q)) {
      # output$question_text <- renderText({next_q$`Question Text`})
    } else {
      # output$question_text <- renderText("No more questions.")
      app_data$complete <- TRUE
    }

    # update results table
    # output$results_table <- renderDataTable({app_data$results})
  })

  observeEvent(input$toggle_splash, {
      app_data$splash <- !app_data$splash
      if (app_data$splash) {
          shinyjs::removeClass("splash-overlay", "slideInLeft")
          shinyjs::removeClass("app-main", "slideOutRight")
          shinyjs::addClass("app-main", "slideInRight")
          shinyjs::addClass("splash-overlay", "slideOutLeft")
      } else {
          shinyjs::removeClass("splash-overlay", "slideOutLeft")
          shinyjs::removeClass("app-main", "slideInRight")
          shinyjs::addClass("app-main", "slideOutRight")
          shinyjs::addClass("splash-overlay", "slideInLeft")
      }
  })
}

shinyApp(ui = ui, server = server)
