wrap_plotly_title <- function(title, width, type = "normal") {
  if(type == "yaxis"){
    max_chars <- ifelse(width <= 767, 30, 50)
  } else {
    max_chars <- ifelse(width <= 767, 40, 100)
  }
  line_break <- "<br>"
  
  words <- strsplit(title, " ")[[1]]
  
  new_title <- ""
  current_line <- ""
  
  for (word in words) {
    if (nchar(current_line) + nchar(word) + 1 > max_chars) {
      new_title <- paste0(new_title, trimws(current_line), line_break)
      current_line <- word
    } else {
      current_line <- paste(current_line, word)
    }
  }
  
  new_title <- paste0(new_title, trimws(current_line))
  
  return(new_title)
}

custom_plotly <- function(..., xaxis_title, yaxis_title, width, hover_info = TRUE) {
  p <- plot_ly(...) %>%
    layout(
      xaxis = list(
        title = list(text = wrap_plotly_title(xaxis_title, width), standoff = 10),
        fixedrange = TRUE,
        automargin = TRUE,
        tickangle = ifelse(width <= 767, 90, "auto")
      ),
      yaxis = list(
        title = list(text = wrap_plotly_title(yaxis_title, width, "yaxis"), standoff = 10),
        rangemode = "tozero",
        tickformat = ",d",
        fixedrange = TRUE
      ),
      legend = list(
        orientation = "h",
        xanchor = "center",
        x = 0.5,
        y = ifelse(width <= 767, -0.4, -0.25)
      ),
      autosize = TRUE,
      dragmode = FALSE
    ) %>%
    config(
      displayModeBar = FALSE,
      responsive = TRUE,
      scrollZoom = FALSE,
      doubleClick = FALSE
    )
  if (hover_info == TRUE){
    p <- p %>%
      style(hovertemplate = "%{x}<br>%{y}<extra></extra>", legendgroup = NULL)
  }
  
  return(p)
}

regression_coefficient_data <- function(regression_result){
  coef_plot <- tidy(coeftest(regression_result, vcov = vcovHC, type = "HC1")) %>%
    mutate(conf.low = estimate - 1.96 * std.error,
           conf.high = estimate + 1.96 * std.error) %>%
    filter(p.value < 0.1)
  
  return(coef_plot)
}

coefficient_plot_function <- function(regression_result, coefficient_plotting_data = NULL, width, range_val = 10) {
  
  if (!is.null(regression_result)) {
    coefficient_plotting_data <- regression_coefficient_data(regression_result)
  }
  
  coefficient_plotting_data <- coefficient_plotting_data %>%
    mutate(term = gsub("_", " ", term))
  
  custom_plotly(
    data = coefficient_plotting_data,
    x = ~estimate,
    y = ~reorder(term, estimate),
    type = "scatter",
    mode = "markers",
    marker = list(size = 10),
    error_x = list(
      type = "data",
      symmetric = FALSE,
      array = ~conf.high - estimate,
      arrayminus = ~estimate - conf.low
    ),
    hovertemplate = paste(
      "<b>%{y}</b><br>",
      "Estimate: %{x:.3f}<br>",
      "<extra></extra>"
    ),
    xaxis_title = "Estimated coefficient",
    yaxis_title = "",
    width = width,
    hover_info = FALSE
  ) %>%
    layout(autosize = FALSE,
           margin = list(
             l = 225
           ),
      xaxis = list(
        range = c(-range_val, range_val),
        zeroline = FALSE,
        fixedrange = TRUE
      ),
      yaxis = list(
        title = ""
      ),
      shapes = list(
        list(
          type = "line",
          x0 = 0, x1 = 0,
          y0 = 0, y1 = 1,
          yref = "paper",
          line = list(
            color = "grey50",
            dash = "dash"
          )
        )
      ),
      showlegend = FALSE
    )
}

# coefficient_plot_function <- function(regression_result, coefficient_plotting_data = NULL){
#   if (!is.null(regression_result)){
#     coefficient_plotting_data <- regression_coefficient_data(regression_result)
#   }
# 
#   plot_ly(
#     data = coefficient_plotting_data,
#     x = ~estimate,
#     y = ~reorder(term, estimate),
#     type = "scatter",
#     mode = "markers",
#     marker = list(size = 10),
#     error_x = list(
#       type = "data",
#       symmetric = FALSE,
#       array = ~conf.high - estimate,
#       arrayminus = ~estimate - conf.low
#     ),
#     hovertemplate = paste(
#       "<b>%{y}</b><br>",
#       "Estimate: %{x:.3f}<br>",
#       "<extra></extra>"
#     )
#   ) %>%
#     layout(
#       xaxis = list(
#         title = "Estimated coefficient",
#         range = c(-10, 10),
#         zeroline = FALSE
#       ),
#       yaxis = list(
#         title = ""
#       ),
#       shapes = list(
#         list(
#           type = "line",
#           x0 = 0, x1 = 0,
#           y0 = 0, y1 = 1,
#           yref = "paper",
#           line = list(
#             color = "grey50",
#             dash = "dash"
#           )
#         )
#       )
#     )
# }
