library(shiny)
library(shinyjs)
library(shinyAce)
library(bslib)

version <- "1.0.0"

function(req) {
  fluidPage(
    useShinyjs(),
    titlePanel("Dilution Wizard"),
    tags$head(tags$style((".shiny-notification {position: fixed; top: 20%;left: 50%; margin-top: -100px; 
                          margin-left: -250px; color: blue;font-size: 20px; font-style: italic;}")),
      tabsetPanel(id="toptab",
          tabPanel("Data entry",
                   wellPanel(
                     fluidRow(
                       tags$head(tags$style(HTML("label {font-size:80%;margin-bottom: 3px;margin-top: 3px;}"))),
                       column(2,
                              tags$image(src="logo.png", class="adv_logo"),
                              h4("upload EXCEL"),
                              fileInput(inputId = "iFile", label = "", accept="ms-excel"),
                              uiOutput(outputId = "sheetName"),
                              div(checkboxInput("PureErr", "Should pure error be used for calculation of CIs?", FALSE),
                                  style = "font-size: 24px !important;color: red"),
                              verbatimTextOutput("stats"),
                              h5("\n\n\n Author: Franz Innerbichler, InnerAnalytics")),
                       div(id="parameter",
                           column(1,style = "background: lightgrey",
                                  #actionButton("StartCalc", "Click, when calculations to be started"),
                                  h4("curve settings"),
                                  numericInput("lowAsymptREF", "lower asymptote REF",10,step=1,min=0),
                                  numericInput("lowAsymptTEST", "lower asymptote TEST",10,step=1,min=0),
                                  numericInput("uppAsymptREF", "upper asymptote REF",110,step=1,min=0),
                                  numericInput("uppAsymptTEST", "upper asymptote TEST",110,step=1,min=0)
                                  ),
                           column(1,style = "background: lightgrey",
                                  numericInput("slopeREF", "slope REF",1,step=0.1,min=-10),
                                  numericInput("slopeTEST", "slope TEST",1,step=0.1,min=-10),
                                  numericInput("EC50", "EC50 REF",-3.5),
                                  numericInput("potDiff", "potency difference",0)
                           ),
                           column(1,style = "background: lightgreen",
                                  h4("dilutions"),
                                  numericInput("CONC1", "highest concentration",0.3, min=-3.5),
                                  numericInput("CONC2", "2nd concentration",0.15),
                                  numericInput("CONC3", "3rd concentration",0.075),
                                  numericInput("CONC4", "4th concentration",0.0375),
                                  numericInput("CONC5", "5th concentration",0.01875),
                                  
                                  numericInput("CONC6", "6th concentration",0.00938)
                           ),
                           column(1,style = "background: lightgreen",
                               
                                  numericInput("CONC7", "7th concentration",0.00469),
                                  numericInput("CONC8", "8thd concentration",0.00235),
                                  numericInput("CONC9", "9thd concentration",NA),
                                  numericInput("CONC10", "10th concentration",NA),
                                  numericInput("CONC11", "11th concentration",NA),
                                  
                                  numericInput("CONC12", "lowest concentration",NA)
                           ),
                           column(1,style = "background: lightblue",
                                  h4("geometric dilution scheme"),
                                  numericInput("ConcStart", "starting concentration",NA),
                                  numericInput("dilutionFac", "dilution factor",NA),
                                  numericInput("NoDil", "no. of dilutions",NA),
                                  numericInput("NoDilSer", "no. of dil. series",NA),
                                  verbatimTextOutput("dilutions")
                           ),
                           column(4,
                                  h4("log-dilution scheme"),
                                  verbatimTextOutput("logdil"),
                                  h4("User help"),
                                  h5("If new dilutions are entered, please adjust EC50 to avoid calculation errors"))
                           )
                     )
                   )),
                   
                   #### XLSX diagnostics ----
                   tabPanel ("XLSX diagnostics",
                             tags$style(HTML("pre { color: black; background-color: #FFE1FF; 
                                             font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size: 12px;} ")),
                             wellPanel(
                               fluidRow(
                                 column(2, 
                                        h5("Diagnostics only shown if EXCEL is uploaded"),
                                        htmlOutput("PureErrW2"), 
                                        tags$head(tags$style("#PureErrW2{color: red;
                                                             font-size: 16px;
                                                             font_style: italic;}")),
                                        tableOutput("FileSAmpl"),
                                        downloadButton("downloadXLReport", label="Download PDF report", class="butt"),
                                        tags$style(type="text/css","#downloadXLReport {background-color: orange; color: black;font-family: COurier New}"),
                                        plotOutput("relpotTestPlot", width="300px", height="150px"),
                                        h4("Akaike Information Criterion"),
                                        tableOutput("AIC"),
                                        h5("First row: restricted model; 2nd row: unrestricted model"),
                                        h5("Smaller values of AIC indicate better fit to the data"),
                                        tableOutput("VarDiagn")
                                        ),
                                 column(4,
                                        plotOutput("XLplot"),
                                        column(6,
                                               br(),
                                               "Regression results restricted",
                                               tableOutput("coeffs_r"),
                                               "Bend points restricted",
                                               tableOutput("coeffs_r2")),
                                       column(6,
                                              br(),
                                              "Regression results unrestricted",
                                              tableOutput("coeffs_unr"))),
                                 column(4,
                                        plotOutput("diagnplot"),
                                        column(6,
                                               tableOutput("logcoeffs_r"),
                                               tableOutput("coeffs_unr2")),
                                               column(6,
                                                      tableOutput("logcoeffs_unr"))),
                                 column(2,
                                        tableOutput("ANOVAXLS"),
                                        DT::renderDataTable("EQtests"))
                             )
                             )),
                   #### 4pl fits ----
                   tabPanel("4pl-fit",
                             wellPanel(
                               fluidRow(
                                 column(6,
                                        tags$style(span(htmlOutput("PureErrW3"), style="color: red")),
                                                   htmlOutput("PureErrW3"),
                                                   tags$head(tags$style("#PureErrW2{color: red;
                                                             font-size: 16px;
                                                             font_style: italic;}")),
                                                   plotOutput("plot"),
                                                   DT::dataTableOutput("pottab4pl"),
                                                                       "Footnote: test performed on absolute CIs."),
                                 column(6,
                                        DT::dataTableOutput("secondary"), # SSTs
                                        h5("*...The estimate for F-test on regression and on non-linearity is the p-value"),
                                        h5("F-test on regression passes if F-value > F-crit and thus p < 0.05"),
                                        h5("F-test on non-linearity passes if F-value < F-crit and thus p > 0.05"),
                                        h5("Test results outcome: 0 ... test passed (for EQ tests: CI within limits);
                                           1 ... test failed (for EQ tests CI not within limits);
                                           -1 ... calculations unbound/denominator too close to 0"),
                                        #plotOutput("CIplot, height=50%")
                                        )                  
                                 ))
                               ),
                   #### Linear PLA ----
                   tabPanel("Linear PLA",
                            wellPanel(
                              fluidRow(
                                column(6,
                                       htmlOutput("PureErrW3"),
                                       tags$head(tags$style("#PureErrW2{color: red;
                                                             font-size: 16px;
                                                             font_style: italic;}")),
                                       plotOutput("plotLin"),
                                       "Delta method is used for potency CIs",
                                       DT::dataTableOutput("pottab"),
                                       h4("Unrestricted linear model (SSSI):"),
                                       tableOutput("SummaryModABu"),
                                       h4("Restricted linear model (CSSI):"),
                                       tableOutput("SummaryModAB")),
                                column(3,
                                       h3("Tests for linear PLA):"),
                                       DT::dataTableOutput("TESTSlin"),
                                       h5("The estimate is the p-value of the test"),
                                       h5("F-tests on regression, significance of slopes, and preparation need to have a p-value <0.05 to pass"),
                                       h5("All other tests pass if p-value > 0.05"),
                                       "SST CI for difference of slopes:",
                                       tableOutput("SlopeDiffCI")),
                                column(3,
                                       h3("ANOVA for parallel line assay"),
                                       DT::dataTableOutput("ANOVAlin"))
                              )
                            )),
                   #### Dilution simulator ----
                   tabPanel("Dilution simulator",
                            wellPanel(
                              fluidRow(
                                column(4,
                                       h3("Confidence intervals"),
                                       tableOutput("CIs"),
                                       "The confidence intrval table is interaactive for changes in: variability slider (%SD), potency of test-slider,
                                       and 'Adjust the dilutions'-slider",
                                       tableOutput("optimalDils"),
                                       selectInput(inputId="scenario", label= "Select an 'optimal' scenario:", choices = c("scenario 2","scenario 3","scenario 6","steep slope"))),
                                column(5,
                                       plotOutput("plotfordilutions"),
                                       h4("in grey: most extreme bend point lines of theoretical samples with 50% and 200% potency"),
                                       sliderInput("dilslider", "Adjust the dilutions(+-change in %)", min = -100,max=100, value=0, step=1, round=0),
                                       checkboxInput("fixupper","Fix highest concentration (if unticked, the center is fixed)",FALSE),
                                       h5("Dilution factors"),
                                       tableOutput("adjlogdil"),
                                       "Short guidance: wider dilution ranges increase the CIs of rel. potency, and decrease the CIs of upper and lower asymptote ratios, as well as Hill's slope ratios", br(),
                                       "Narrower dilution ranges decrease the CIs of rel. potency, and increase the CIs of upper and lower asymptote ratios, ands Hill's slope ratios",),
                                column(3,
                                       h3("Bend points"),
                                       tableOutput("bps"),
                                       tableOutput("extremebps"),
                                       h4("Explanation of the plots")
                                       )
                              )
                            )),
                   #### EQ limits simulation ----
                   tabPanel("EQ-limit simulatioin",
                            wellPanel(
                              fluidRow(
                                column(1, style="background: lightblue",
                                       numericInput("simN","number of datasets to simulate", 100, step=10, min=10, max=1000),
                                       numericInput("lowQuant", "lower quantile", 1, min = 0.01,max=20),
                                       numericInput("uppQuant", "upper quantile", 99, min = 801,max=99.99),
                                       actionButton('goSim', "Start simulation",class="btn-success")
                                       ),
                                column(4,
                                       h4("estimation of EACs for slope ratio, dynamic range-ratio, upper asymptote ratio, and potency"),
                                       plotOutput("plotHistuAs", width = "1400px", height = "400px"))
                              )
                            )),
                   #### Documentation ----
                   tabPanel("Documentation",
                            h4("Information on dilution setting"),
                            "(for details see:", a(href="ADONIS.pdf","Whitepaper", download=NA, target="_blank"),")",tags$br(),
                            "Bend points are calculated according to following formula:",
                            withMathJax(" $$bp_{1/2} = \\pm\\frac{1.31696}{Hill's slope}$$"))),
                             
   #### setting lower panel ----
   wellPanel(
     fluidRow(
       column(2,
              h3("Settings"),
              helpText("Vary the slider to see the effect of special cause"),
              sliderInput("sdfac","Variability as % of lower to upper asymptote", max=10, value=3, min=0.1, step=0.1),
              checkboxInput("heterosked","heteroskedastic noise", FALSE),
              sliderInput("potencydiff","potency of test (%)", max=200, min=50, value=100, step=1),
              sliderInput("outlL","outlier in lower asymptote",  min=0, max=1.5, value=0, step=0.1),
              sliderInput("outlM","outlier in mid part",   min=0, max=1.5,value=0, step=0.1),
              sliderInput("outlU","outlier in upper asymptote",   min=0, max=1.5,value=0, step=0.1)
              ),
       column(1,
              tags$table(id="dose-table",
                         numericInput("lEACdiffla","lower EAC for diff. of LA", -0.175, step=0.001),
                         numericInput("uEACdiffla","upper EAC for diff. of LA", 0.189, step=0.001),
                         numericInput("lEACratiola","lower EAC ratio of LAs", 0.005, step=0.001),
                         numericInput("uEACratiola","upper EAC for ratio of LAs", 100, step=1),
                         
                         numericInput("lEACratioSlope","lower EAC for ratio of slopes", 0.55, step=0.01),
                         numericInput("uEACratioSlope","upper EAC for ratio of slopes", 1.84, step=0.1),
                         numericInput("lEACratioua","lower EAC for ratio of UAs", 0.75, step=0.1),
                         numericInput("uEACratioua","upper EAC for ratio of UAs", 1.33, step=0.1),
                         numericInput("lowerPot","lower EAC for potency", 75, step=1),
                         numericInput("upperPot","upper EAC for potency", 133, step=1),
                         numericInput("lEACratioAdiff","lower EAC of ratio of asymptote differences", 0.75, step=0.01),
                         numericInput("uEACratioAdiff","upper EAC of ratio of asymptote differences", 1.33, step=0.01)
                         )),
       column(4,
              "4 PL ANOVA unrestricted",
              DT::dataTableOutput("ANOVA"),
              h5("Please note that for the CIs of rel. potency the RSS of the restricted model is used"),
              h5("RSS ... 'Residual error' in the SumSquares column"),
              h5("MSE ... 'Residual error' in the MSs column"),
              h5("SSE ... 'Pure error' in the SumSquares column"),
              h5("RMSE ... Square root of the 'Residual Error' in the MS column"),
              verbatimTextOutput("RMSE")
              ),
       column(5,
              DT::dataTableOutput("Conctab"))
     )
   )
                   
                   
                   )
  )
}