# Cargar paquetes necesarios
library(shiny)
library(pROC)
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
library(ggplot2)

# Ejemplo de datos
set.seed(123)
datos <- data.frame(
  variable_1 = sample(0:1, 100, replace = TRUE),
  variable_2 = sample(0:1, 100, replace = TRUE),
  variable_3 = sample(0:1, 100, replace = TRUE),
  diagnostico = factor(sample(c("Positivo", "Negativo"), 100, replace = TRUE))
)

# Ajustar el modelo de regresión logística
modelo_viruela_mono <- glm(diagnostico ~ variable_1 + variable_2 + variable_3, data = datos, family = binomial())

# Crear la curva ROC
roc_viruela_mono <- roc(datos$diagnostico, fitted(modelo_viruela_mono))
## Setting levels: control = Negativo, case = Positivo
## Setting direction: controls < cases
# Encontrar el umbral óptimo
coords <- coords(roc_viruela_mono, "best", ret = c("threshold", "ppv", "npv", "sensitivity", "specificity"))
optimal_threshold <- coords["threshold"]

# Interfaz de usuario
ui <- fluidPage(
  titlePanel("Diagnóstico de Viruela del Mono"),
  sidebarLayout(
    sidebarPanel(
      radioButtons("variable_1", "Variable clínica 1:", choices = c("Ausente" = 0, "Presente" = 1), selected = ""),
      radioButtons("variable_2", "Variable clínica 2:", choices = c("Ausente" = 0, "Presente" = 1), selected = ""),
      radioButtons("variable_3", "Variable clínica 3:", choices = c("Ausente" = 0, "Presente" = 1), selected = ""),
      actionButton("predecir", "Predecir")
    ),
    mainPanel(
      h3("Diagnóstico probable:", align = "center"),
      h2(textOutput("texto_prediccion"), align = "center", style = "color: red; font-weight: bold;"),
      textOutput("texto_vpp"),
      textOutput("texto_vpn"),
      textOutput("texto_sensibilidad"),
      textOutput("texto_especificidad"),
      plotOutput("plot_roc")
    )
  )
)

# Lógica del servidor
server <- function(input, output) {
  observeEvent(input$predecir, {
    nuevo_datos <- data.frame(
      variable_1 = as.numeric(input$variable_1),
      variable_2 = as.numeric(input$variable_2),
      variable_3 = as.numeric(input$variable_3)
    )
    probabilidad_predicha <- predict(modelo_viruela_mono, nuevo_datos, type = "response")
    clase_predicha <- as.integer(probabilidad_predicha > optimal_threshold)
    diagnostico <- ifelse(clase_predicha == 0, "Negativo", "Positivo")
    output$texto_prediccion <- renderText(diagnostico)

    vpp <- coords["ppv"]
    vpn <- coords["npv"]
    sensibilidad <- coords["sensitivity"]
    especificidad <- coords["specificity"]

    output$texto_vpp <- renderText(paste("Valor Predictivo Positivo:", round(vpp, 2)))
        output$texto_vpn <- renderText(paste("Valor Predictivo Negativo:", round(vpn, 2)))
    output$texto_sensibilidad <- renderText(paste("Sensibilidad:", round(sensibilidad, 2)))
    output$texto_especificidad <- renderText(paste("Especificidad:", round(especificidad, 2)))

    output$plot_roc <- renderPlot({
      ggroc(roc_viruela_mono) +
        geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
        geom_point(aes(x = 1 - especificidad, y = sensibilidad, color = "red"), size = 4) +
        labs(
          title = "Curva ROC - Diagnóstico de Viruela del Mono",
          subtitle = paste0("Umbral óptimo: ", round(optimal_threshold, 2)),
          x = "1 - Especificidad",
          y = "Sensibilidad",
          color = ""
        ) +
        theme_minimal()
    })
  })
}

# Ejecutar la aplicación Shiny
shinyApp(ui = ui, server = server)
## 
## Listening on http://127.0.0.1:3791