box::use(
  shiny[tagList, fluidRow, HTML, column,p, br, div, moduleServer, NS, selectInput, textOutput, renderText, tags, dateRangeInput, checkboxInput,
        downloadButton, observeEvent, reactive, observe, showModal, modalDialog,modalButton, bindCache, req, reactiveVal ],
  shinydashboard[valueBoxOutput, renderValueBox, valueBox],
  bslib[value_box],
  shinycssloaders[withSpinner],
  shinyBS[bsModal, toggleModal, ],
  DT[DTOutput, renderDT, datatable],
  datasets[mtcars],
  shinyjs[useShinyjs, show, hide, hidden, enable, disable, disabled],
  shinyWidgets[actionBttn],
  reactable[reactableOutput, renderReactable, reactable, colDef, JS, getReactableState, reactableTheme, reactableLang],
  stringr[str_extract]
)

box::use(
  app/data_prep/data_fcts[clean_genotype_columns]
)

#' @export
ui <- function(id) {
  ns <- NS(id)
  tagList(
    div(
      useShinyjs(),
      value_box(
        title = textOutput(ns("title")),
        value = textOutput(ns("value")),
        theme = "primary",
        textOutput(ns("uniq")),
        textOutput(ns("biparental")),
        textOutput(ns("backcross")),
        textOutput(ns("multiparental")),
        showcase = tagList(
          actionBttn(
            inputId = ns("my_button"),
            label = "Details",
            style = "bordered",
            color = "default",
            size = "xs",
            block = TRUE,
            no_outline = TRUE
          )
        ),
        showcase_layout = "bottom" # Position the button at the bottom
        )
    ),

     bsModal("modalExample", "Data Table", "my_button", size = "large",
             reactableOutput(ns("table")) |>
               withSpinner(type = 7, size = 1)
         )

  )
}

#' @export
server <- function(id, title, controls ) {
  moduleServer(id, function(input, output, session) {

    data <- reactiveVal(NULL)

    observe({
      if (!is.null(controls$site) && controls$site !="") {
      data(data_input())
      }
    })

    data_input <- reactive({
      data <- readRDS(paste0("app/data/",tolower(controls$site), "_crosses.rds"))
      if (controls$site !="All") {
        data <- data |>
          dplyr::filter(Location == controls$site)
        } else {
          data <- data
        }

        start_ <- lubridate::ymd(controls$daterange[1])
        end_ <- lubridate::ymd(controls$daterange[2])

        data |>
          clean_genotype_columns() |>
          dplyr::filter(dplyr::between(First_Pollination_Date, start_, end_))

    })

    bi_parental <- reactive({
      data_input() |>
        dplyr::filter( Cross_Type == "Bi-Parental")
    })


    backcross <- reactive({
      data_input() |>
        dplyr::filter( Cross_Type == "Back-Cross")
    })


    multi_parental <- reactive({
      data_input() |>
        dplyr::filter( Cross_Type == "Multi-Parental")
    })


    uniq_input <- reactive({
      data_input() |>
        dplyr::group_by(Female_Genotype, Male_Genotype) |>
        dplyr::tally()
    })


    observeEvent(controls$site , {
      if(nrow(multi_parental())>0){
        show("multiparental")
      } else {
        hide("multiparental")
      }

      if(nrow(backcross())>0){
        show("backcross")
      } else {
        hide("backcross")
      }
    })

    output$title<- renderText({
      req(controls$site)
      title
    })

    output$value<- renderText({
      req(controls$site)
      nrow(data_input())
    })


    output$uniq<- renderText({
      req(controls$site)
      paste(nrow(uniq_input())," Unique combinations")
    })

    output$biparental<- renderText({
      req(controls$site)
      paste(nrow(bi_parental())," Bi-Parental")
    })


    output$backcross<- renderText({
      req(controls$site)
      paste(nrow(backcross())," Back crosses")
    })


    output$multiparental<- renderText({
      req(controls$site)
      paste(nrow(multi_parental())," Multi-Parental")
    })



    observeEvent(input$my_button, {
      # Trigger the modal when the action button is clicked
      showModal(modalDialog(
        title = title,

        renderReactable({
          reactable(
            data_input(),
            defaultColDef = colDef(minWidth = 100, maxWidth = 200, width = 150,
                                   headerStyle = list(color = "hsl(203, 15%, 47%)")),
            columns = list(
              `Female Genotype` = colDef(html = TRUE, cell = function(value, index) {
                sprintf('<a href="%s" target="_blank">%s</a>', dt$`Female URL`[index], value)
              }),
              `Male Genotype` = colDef(html = TRUE, cell = function(value, index) {
                sprintf('<a href="%s" target="_blank">%s</a>', dt$`Male URL`[index], value)
              }),
              `Female URL` = colDef(show = FALSE),
              `Male URL` = colDef(show = FALSE)
            ),
            filterable = TRUE,
            searchable = TRUE,
            selection = "multiple",
            onClick = "select",
            minRows = 10,
            highlight = TRUE,
            language = reactableLang(
              noData = "No data found",
              pageInfo = "{rowStart}\u2013{rowEnd} of {rows} data"
            ),
            theme = reactableTheme(
              highlightColor = "#f3fafb",
              borderColor = "hsl(0, 0%, 93%)",
              headerStyle = list(borderColor = "hsl(0, 0%, 90%)")
            )
          )
        }),
        # reactable(
        #   dt,
        #   defaultColDef = colDef(minWidth = 100, maxWidth = 200, width = 150,
        #                          headerStyle = list(color = "hsl(203, 15%, 47%)")),
        #   columns = list(
        #     `Female Genotype` = colDef(html = TRUE, cell = function(value, index) {
        #       sprintf('<a href="%s" target="_blank">%s</a>', dt$`Female URL`[index], value)
        #     }),
        #     `Male Genotype` = colDef(html = TRUE, cell = function(value, index) {
        #       sprintf('<a href="%s" target="_blank">%s</a>', dt$`Male URL`[index], value)
        #     }),
        #     `Female URL` = colDef(show = FALSE),
        #     `Male URL` = colDef(show = FALSE)
        #   ),
        #   filterable = TRUE,
        #   searchable = TRUE,
        #   selection = "multiple",
        #   onClick = "select",
        #   minRows = 10,
        #   highlight = TRUE,
        #   language = reactableLang(
        #     noData = "No data found",
        #     pageInfo = "{rowStart}\u2013{rowEnd} of {rows} data"
        #   ),
        #   theme = reactableTheme(
        #     highlightColor = "#f3fafb",
        #     borderColor = "hsl(0, 0%, 93%)",
        #     headerStyle = list(borderColor = "hsl(0, 0%, 90%)")
        #   )
        # )
        size = "xl",
        easyClose = TRUE,
        footer = modalButton("Dismiss"),
        fade = TRUE  # No footer buttons
      ))
    })

    data

  })
}
