# Green dashboard page
shinydashboard::dashboardPage(
  skin = "green",

  # Dashboard header and title
  shinydashboard::dashboardHeader(
    title = "BayesianNetwork"
  ),

  # Dashboard sidebar
  shinydashboard::dashboardSidebar(

    # Sidebar menu
    shinydashboard::sidebarMenu(
      id = "sidebarMenu",

      # Home menu item
      shinydashboard::menuItem(
        "Home",
        tabName = "home",
        icon = shiny::icon("home")
      ),

      # Structure menu item
      shinydashboard::menuItem(
        "Structure",
        icon = shiny::icon("globe"),
        tabName = "structure"
      ),

      # Parameters menu item
      shinydashboard::menuItem(
        "Parameters",
        tabName = "parameters",
        icon = shiny::icon("bar-chart")
      ),

      # Inference menu item
      shinydashboard::menuItem(
        "Inference",
        icon = shiny::icon("arrow-right"),
        tabName = "inference"
      ),

      # Measures menu item
      shinydashboard::menuItem(
        "Measures",
        tabName = "measures",
        icon = shiny::icon("table")
      ),

      # # Editor menu item
      # shinydashboard::menuItem(
      #   "Editor",
      #   tabName = "editor",
      #   icon = shiny::icon("code")
      # ),
      br(),

      # Help page link
      shinydashboard::menuItem("Help",
                               icon = icon("info-circle"),
                               href = "http://paulgovan.github.io/BayesianNetwork/"),

      # Source code link
      shinydashboard::menuItem("Source Code",
                               icon = icon("github"),
                               href = "https://github.com/paulgovan/BayesianNetwork"),

      # Bookmark button
      shiny::br(),
      shiny::bookmarkButton(id = "bookmark"),
      tags$style(type='text/css', "#bookmark { display: block; margin: 0 auto; }")

    )
  ),

  # Dashboard body
  shinydashboard::dashboardBody(
    id = "dashboardBody",

    # Add favicon and title to header
    tags$head(
      tags$link(rel = "icon", type = "image/png", href = "favicon.png"),
      tags$title("BayesianNetwork")
    ),

    # Include introjs UI
    rintrojs::introjsUI(),

    # Dashboard tab items
    shinydashboard::tabItems(

      # Home tab item
      shinydashboard::tabItem(
        tabName = "home",
        shiny::fluidRow(

          # Welcome box
          shinydashboard::box(
            title = "",
            status = "success",
            width = 8,
            shiny::img(src = "favicon.png",
                       height = 200,
                       width = 175
            ),
            shiny::h2("BayesianNetwork"),
            shiny::h4("Bayesian Network Modeling and Analysis"),
            br(),
            shiny::h4("BayesianNetwork is a ",
                      shiny::a(href = 'http://shiny.rstudio.com', 'shiny'),
                      "web application for Bayesian network modeling and analysis, powered by",
                      shiny::a(href = 'http://www.bnlearn.com', 'bnlearn'),
                      'package.'
            ),
            shiny::h4("Click",
                      shiny::a("Structure", href="#shiny-tab-structure", "data-toggle" = "tab"),
                      " in the sidepanel to get started."
            ),
            br(),
            # Add introjs btn
            shiny::actionButton("homeIntro", "Show me how it works"),
            tags$style(type='text/css', "#homeIntro { display: block; margin: 0 auto; }")
          ),

          # Nodes and arcs value boxes
          shiny::uiOutput("nodesBox"),
          shiny::uiOutput("arcsBox")
        )
      ),

      # Structure tab item
      shinydashboard::tabItem(tabName = "structure",
                              shiny::fluidRow(
                                shiny::column(
                                  width = 4,

                                  # Network input box
                                  shinydashboard::box(
                                    title = "Data Input",
                                    status = "success",
                                    collapsible = TRUE,
                                    width = NULL,
                                    shiny::helpText("Select a sample network or upload your Bayesian network data:"),

                                    shinyWidgets::radioGroupButtons(inputId = "dataInput",
                                                                    choices = c("Sample Network" = 1,
                                                                                "Upload Data" = 2),
                                                                    selected = 1,
                                                                    justified = TRUE
                                                                    ),

                                    # Conditional panel for sample network selection
                                    shiny::conditionalPanel(
                                      condition = "input.dataInput == 1",

                                      # Demo network input select
                                      shiny::selectInput(
                                        inputId = "net",
                                        h5("Bayesian Network:"),
                                        c("Sample Discrete Network" = 1,
                                          "Sample Gaussian Network" = 2,
                                          "Alarm Network" = 3,
                                          "Insurance Network" = 4,
                                          "Hailfinder Network" = 5
                                        )
                                      )
                                    ),

                                    # Conditional panel for file input selection
                                    shiny::conditionalPanel(
                                      condition = "input.dataInput == 2",

                                      shiny::p('Note: your data should be structured as a csv file with header of variable names.'
                                      ),

                                      # File input
                                      shiny::fileInput(
                                        'file',
                                        strong('File Input:'),
                                        accept = c('text/csv',
                                                   'text/comma-separated-values',
                                                   'text/tab-separated-values',
                                                   'text/plain',
                                                   '.csv',
                                                   '.tsv'
                                        )
                                      )
                                    )
                                  ),

                                  # Structural learning box
                                  shinydashboard::box(
                                    title = "Structural Learning",
                                    status = "success",
                                    collapsible = TRUE,
                                    width = NULL,
                                    shiny::helpText("Select a structural learning algorithm:"),

                                    # Structural learning algorithm input select
                                    shiny::selectizeInput(
                                      inputId = "alg",
                                      shiny::h5("Learning Algorithm:"),
                                      choices = list(
                                        "Constraint-based Learning" =
                                          c("Grow-Shrink" = "gs",
                                            "Incremental Association" = "iamb",
                                            "Fast IAMB" = "fast.iamb",
                                            "Inter IAMB" = "inter.iamb"
                                          ),
                                        "Score-based Learning" =
                                          c("Hill Climbing" = "hc",
                                            "Tabu" = "tabu"),
                                        "Hybrid Learning" =
                                          c("Max-Min Hill Climbing" = "mmhc",
                                            "2-phase Restricted Maximization" = 'rsmax2'
                                          ),
                                        "Local Discovery Learning" =
                                          c("Max-Min Parents and Children" = 'mmpc',
                                            "Semi-Interleaved HITON-PC" = "si.hiton.pc",
                                            "ARACNE" = "aracne",
                                            "Chow-Liu" = "chow.liu"
                                          )
                                      )
                                    ),
                                    shiny::uiOutput("algHelp")
                                  ),

                                  # Network score box
                                  shinydashboard::box(
                                    title = "Network Score",
                                    status = "success",
                                    collapsible = TRUE,
                                    width = NULL,

                                    # Network score function input select
                                    shiny::selectInput(
                                      "type",
                                      h5("Network Score:"),
                                      c("Log-Likelihood" = "loglik",
                                        "Akaike Information Criterion" = "aic",
                                        "Bayesian Information Criterion" = "bic",
                                        "Bayesian Equivalent" = "be"
                                      ), 'loglik-g'
                                    ),

                                    # Network score output
                                    shiny::verbatimTextOutput("score")
                                  )
                                ),
                                shiny::column(
                                  width = 8,

                                  # Bayesian network box
                                  shinydashboard::box(
                                    title = "Bayesian Network",
                                    status = "success",
                                    collapsible = TRUE,
                                    width = NULL,

                                    # d3 force directed network
                                    networkD3::simpleNetworkOutput("netPlot"),
                                    shiny::downloadButton("downloadArcs", "Download Arcs"),
                                    shiny::br(), shiny::br(),
                                    shiny::downloadButton("downloadBIF", "Download Network (BIF)")
                                  )
                                )
                              ),

                              # Add introjs btn
                              shiny::actionButton("structureIntro", "Show me how")
      ),

      # parameters tab item
      shinydashboard::tabItem(tabName = "parameters",
                              shiny::fluidRow(
                                shiny::column(
                                  width = 4,

                                  # parameter learning box
                                  shinydashboard::box(
                                    title = "Parameter Learning",
                                    status = "success",
                                    collapsible = TRUE,
                                    width = NULL,
                                    shiny::helpText("Select a parameter learning method:"),

                                    # Parameter learning method input select (hidden for continuous data)
                                    shiny::conditionalPanel(
                                      condition = "output.isNumericData === false",
                                      shiny::selectInput(
                                        "met",
                                        shiny::h5("Learning Method:"),
                                        c("Maximum Likelihood Estimation" = "mle",
                                          "Bayesian Estimation" = "bayes"
                                        )
                                      )
                                    )
                                  ),

                                  # Parameter infographic box
                                  shinydashboard::box(
                                    title = "Parameter Graphic",
                                    status = "success",
                                    collapsible = TRUE,
                                    width = NULL,
                                    helpText("Select a parameter infographic:"),

                                    # Parameter infographic input select
                                    selectInput("param", label = h5("Parameter Infographic:"),
                                                ""),

                                    # Conditional panel for discrete data
                                    shiny::conditionalPanel(
                                      "input.param == 'barchart' || input.param == 'dotplot'",

                                      # Node input select
                                      shiny::selectInput("Node", label = shiny::h5("Node:"), "")
                                    )
                                  )
                                ),
                                shiny::column(
                                  width = 8,

                                  # Network parameters box
                                  shinydashboard::box(
                                    title = "Network Parameters",
                                    status = "success",
                                    collapsible = TRUE,
                                    width = NULL,

                                    # Conditional PD plot
                                    shiny::plotOutput("condPlot"),
                                    shiny::br(),
                                    shiny::downloadButton("downloadParams", "Download Parameters (.rds)")
                                  )
                                )
                              ),

                              # Add introjs btn
                              shiny::actionButton("parametersIntro", "Show me how")
      ),

      # Inference tab item
      shinydashboard::tabItem(tabName = "inference",
                              shiny::fluidRow(
                                shiny::column(
                                  width = 4,

                                  # Evidence box
                                  shinydashboard::box(
                                    title = "Evidence",
                                    status = "success",
                                    collapsible = TRUE,
                                    width = NULL,
                                    shiny::helpText("Select evidence to add to the model:"),
                                    shiny::fluidRow(
                                      shiny::column(6,
                                        shiny::selectInput(
                                          "evidenceNode", label = shiny::h5("Evidence Node:"),
                                          ""
                                        )
                                      ),
                                      shiny::column(6,
                                        shiny::uiOutput("evidenceValueUI")
                                      )
                                    ),
                                    shiny::fluidRow(
                                      shiny::column(6,
                                        shiny::actionButton("addEvidence", "Add", icon = shiny::icon("plus"), class = "btn-success btn-sm")
                                      ),
                                      shiny::column(6,
                                        shiny::actionButton("clearEvidence", "Clear All", icon = shiny::icon("times"), class = "btn-danger btn-sm")
                                      )
                                    ),
                                    shiny::br(),
                                    shiny::strong("Active Evidence:"),
                                    shiny::uiOutput("evidencePanel"),
                                    shiny::br(),
                                    shiny::helpText("Use 'Add' to accumulate multiple evidence nodes. If no evidence is added, the current selection is used directly.")
                                  ),

                                  # Event box
                                  shinydashboard::box(
                                    title = "Event",
                                    status = "success",
                                    collapsible = TRUE,
                                    width = NULL,
                                    helpText("Select an event of interest:"),

                                    # Event node input select
                                    shiny::selectInput("event", label = shiny::h5("Event Node:"),
                                                       "")
                                  )
                                ),
                                shiny::column(
                                  width = 8,

                                  # Event parameter box
                                  shinydashboard::box(
                                    title = "Event Parameter",
                                    status = "success",
                                    collapsible = TRUE,
                                    width = NULL,

                                    # Event conditional PD plot
                                    shiny::plotOutput("distPlot"),
                                    shiny::downloadButton("downloadInference", "Download Results")
                                  )
                                )
                              ),

                              # Add introjs btn
                              shiny::actionButton("inferenceIntro", "Show me how")
      ),

      # Measures tab item
      shinydashboard::tabItem(tabName = "measures",
                              shiny::fluidRow(

                                # Measure controls box
                                shinydashboard::box(
                                  title = "Controls",
                                  status = "success",
                                  collapsible = TRUE,
                                  width = 4,
                                  shiny::helpText("Select a node measure:"),

                                  # Node measure input select
                                  shiny::selectInput(
                                    "nodeMeasure",
                                    h5("Node Measure:"),
                                    c("Markov Blanket" = "mb",
                                      "Neighborhood" = "nbr",
                                      "Parents" = "parents",
                                      "Children" = "children",
                                      "In Degree" = "in.degree",
                                      "Out Degree" = "out.degree",
                                      "Incident Arcs" = "incident.arcs",
                                      "Incoming Arcs" = "incoming.arcs",
                                      "Outgoing Arcs" = "outgoing.arcs"
                                    )
                                  ),

                                  # Node input select
                                  shiny::selectInput("nodeNames", label = shiny::h5("Node:"),
                                                     ""),
                                  shiny::helpText("Select a network measure:"),

                                  # Network measure input select
                                  shiny::selectInput(
                                    "dendrogram",
                                    h5("Dendrogram:"),
                                    c("Both" = "both",
                                      "Row" = "row",
                                      "Column" = "column",
                                      "None" = "none"
                                    )
                                  )
                                ),

                                # Node measure box
                                shinydashboard::box(
                                  title = "Node Measure",
                                  status = "success",
                                  collapsible = TRUE,
                                  width = 8,

                                  # Node measure output
                                  shiny::verbatimTextOutput("nodeText")
                                ),

                                # Network measure box
                                shinydashboard::box(
                                  title = "Adjacency Matrix",
                                  status = "success",
                                  collapsible = TRUE,
                                  width = 8,

                                  # d3 heatmap
                                  plotly::plotlyOutput("netTable"),
                                  shiny::br(),
                                  shiny::downloadButton("downloadAdjMatrix", "Download Adjacency Matrix")
                                )
                              ),

                              # Add introjs btn
                              shiny::actionButton("measuresIntro", "Show me how")
      )

    )
  )
)
