#' Creation du tableau de l artificialisation OCSGE par type de territoire par departement.
#' @description Graphique de l artificialisation OCSGE par type de territoire par departement.
#'
#' @param millesime_ocsge une annee parmi les millesimes selectionnables par l'utilisateur, au format numerique.
#' @param millesime_population une annee parmi les millesimes selectionnables par l'utilisateur, au format numerique.
#' @param code_reg code de la région sélectionnable par l'utilisateur.
#'
#' @return Un tableau
#' @import COGiter
#'
#' @importFrom COGiter charger_zonage ajouter_typologie filtrer_cog
#' @importFrom dplyr mutate filter select group_by summarise ungroup row_number case_when arrange
#' @importFrom lubridate year as_date
#' @importFrom reactable reactable reactableTheme colDef
#' @importFrom stringr str_split_fixed str_trim
#' @importFrom tidyr pivot_longer pivot_wider
#' @importFrom htmltools div p h2
#' @importFrom htmlwidgets prependContent appendContent
#'
#' @export
#'
#' @examples
#' creer_tableau_1_6(millesime_ocsge = 2016, millesime_population = 2019, code_reg = '52')

creer_tableau_1_6 <- function(millesime_ocsge = NULL, millesime_population = NULL, code_reg = NULL){
  attempt::stop_if(millesime_ocsge, is.null, msg = "millesime_ocsge n'est pas renseign\u00e9")
  attempt::stop_if_not(millesime_ocsge, is.numeric, msg = "millesime_ocsge n'est pas un nombre")
  attempt::stop_if(millesime_population, is.null, msg = "millesime_population n'est pas renseign\u00e9")
  attempt::stop_if_not(millesime_population, is.numeric, msg = "millesime_population n'est pas un nombre")
  attempt::stop_if(code_reg, is.null, msg = "code_reg n'est pas renseign\u00e9")

  # creation de la fonction inverse
  `%notin%` <- Negate(`%in%`)

  # seuils population
  pop_3 <- 40000
  pop_2 <- 10000
  pop_1 <- 2000

  if (is.numeric(code_reg)) {
    code_reg = as.character(code_reg)
  }
  if (code_reg %in% c('52')) {

    # population du millesime
    population <- population_legale %>%
      dplyr::mutate(date=lubridate::year(.data$date)) %>%
      COGiter::filtrer_cog(reg = code_reg) %>%
      dplyr::filter(.data$date == millesime_population,
                    .data$TypeZone =="Communes") %>%
      dplyr::mutate(seuil_pop = dplyr::case_when(
        .data$population_municipale > pop_3  ~ glue::glue("communes de plus\nde ",pop_3," habitants"),
        .data$population_municipale > pop_2  ~ glue::glue("communes entre\n",pop_2," et ",pop_3, " habitants"),
        .data$population_municipale > pop_1  ~ glue::glue("communes entre\n",pop_1," et ",pop_2, " habitants"),
        .data$population_municipale > 0  ~ glue::glue("communes de moins\nde ",pop_1," habitants"),
        TRUE ~ "")
        ) %>%
      dplyr::mutate(seuil_code = dplyr::case_when(
        .data$population_municipale > pop_3  ~ "D",
        .data$population_municipale > pop_2  ~ "C",
        .data$population_municipale > pop_1  ~ "B",
        .data$population_municipale > 0  ~ "A",
        TRUE ~ "")
        ) %>%
      dplyr::rename ("population_n"="population_municipale") %>%
      dplyr::select (-.data$date)

    # table des seuils
    seuil_population <- population %>%
      dplyr::select (.data$CodeZone,.data$seuil_pop)


    # preparation des donnees
    ocsge2 <- ocsge %>%
      dplyr::filter(grepl(millesime_ocsge, .data$date))

    mois <- lubridate::month(ocsge[1,"date"],label=TRUE)

    ocsge2 <- ocsge2 %>%
      dplyr::mutate(date=lubridate::year(lubridate::as_date(.data$date)),
                    espace_naturel= .data$autre_surface_naturelle + .data$surface_en_eau + .data$surface_naturelle_boisee) %>%
      COGiter::filtrer_cog(reg = code_reg) %>%
      dplyr::select (.data$TypeZone,.data$Zone,.data$CodeZone,
                     .data$espace_naturel,.data$espace_agricole,.data$espace_artificialise)  %>%
      dplyr::filter(.data$TypeZone == "Communes")

    ocsge3 <- ocsge2 %>%
      dplyr::left_join(seuil_population) %>%
      mutate(dep = substr(.data$CodeZone,1,2)) %>%
      dplyr::group_by(.data$seuil_pop,.data$dep) %>%
      dplyr::summarise(espace_naturel = sum(.data$espace_naturel, na.rm = T),
                       espace_agricole = sum(.data$espace_agricole, na.rm = T),
                       espace_artificialise = sum(.data$espace_artificialise, na.rm = T)) %>%
      dplyr::ungroup()

    # preparation graphiques
    data1 <- ocsge3 %>%
      tidyr::gather(variable, valeur, .data$espace_naturel:.data$espace_artificialise) %>%
      dplyr::group_by(.data$seuil_pop, .data$dep) %>%
      dplyr::mutate(variable = .data$variable,
                    valeur = .data$valeur/10000,
                    taux = .data$valeur / sum(.data$valeur, na.rm=T)*100) %>%
      dplyr::ungroup()

    # donnees du tableau
    data2 <- data1 %>%
      dplyr::select (.data$seuil_pop,.data$dep,.data$variable,.data$taux) %>%
      tidyr::pivot_wider(names_from = "variable", values_from = "taux", values_fill = 0) %>%
      dplyr::left_join(COGiter::departements %>%
                         dplyr::filter (.data$REG == code_reg) %>%
                         dplyr::select(.data$DEP, .data$NOM_DEP),
                       by=c("dep"= "DEP")) %>%
      dplyr::rename("Departement" = "NOM_DEP") %>%
      dplyr::select (.data$seuil_pop, .data$Departement, .data$espace_artificialise, .data$espace_agricole, .data$espace_naturel)

    data <- data2 %>%
      dplyr::group_by(.data$seuil_pop) %>%
      dplyr::mutate(n = dplyr::row_number(),
                    nmax=(.data$n==max(.data$n))) %>%
      dplyr::ungroup() %>%
      dplyr::mutate(seuil_pop = factor(.data$seuil_pop, levels = c(glue::glue("communes de moins\nde ",pop_1," habitants"),
                                                                   glue::glue("communes entre\n",pop_1," et ",pop_2, " habitants"),
                                                                   glue::glue("communes entre\n",pop_2," et ",pop_3, " habitants"),
                                                                   glue::glue("communes de plus\nde ",pop_3," habitants")))) %>%
      dplyr::arrange(.data$seuil_pop) %>%
      dplyr::mutate(seuil_pop = as.character(.data$seuil_pop)) %>%
      dplyr::mutate(seuil_pop = ifelse(.data$n == 1, .data$seuil_pop, "")) %>%
      dplyr::select(.data$seuil_pop,
                    .data$Departement,
                    .data$espace_artificialise,
                    .data$espace_agricole,
                    .data$espace_naturel,
                    .data$nmax)


    # Render a bar chart with a label on the left
    bar_chart <- function(label, width = "100%", height = "14px", fill = "#00bfc4", background = NULL) {
      bar <- htmltools::div(style = list(background = fill, width = width, height = height))
      chart <- htmltools::div(style = list(flexGrow = 1, marginLeft = "6px", background = background), bar)
      htmltools::div(style = list(display = "flex", alignItems = "center"), label, chart)
    }

    tableau_1_6 <- reactable::reactable(
      data %>% dplyr::select(-.data$nmax),
      defaultPageSize = 100,
      sortable = FALSE,
      rowStyle = function(index) {
        if (data[index, "nmax"] == TRUE) {
          list(borderBottom = "1pt solid #DEDEDE")
          }
        },
      defaultColDef = reactable::colDef(headerStyle = "border-bottom: 2px solid #555;"),
      theme = reactable::reactableTheme(
        style = list(fontFamily = "Marianne")
        ),
      columns = list(
        seuil_pop = reactable::colDef(
          name = "tranche de population"
          ),
        Departement = reactable::colDef(
          name = "D\u00e9partement"
          ),
        espace_agricole = reactable::colDef(
          name = "Espaces agricoles",
          cell = function(value) {
            # Format as percentages with 1 decimal place
            width <- paste0(format(value, nsmall = 1), "%")
            label <- paste0(format(value, nsmall = 1, decimal.mark = ",",digits = 1), "%")
            label <- ifelse(value<10, paste0("0", stringr::str_trim(label)), label)#pour gerer les valeurs à l'unite
            bar_chart(label, width = width, fill = "#E3CE00", background = "#e1e1e1")
            },
          # And left-align the columns
          align = "left"
          ),
        espace_artificialise = reactable::colDef(
          name = "Espaces artificialis\u00e9s",
          cell = function(value) {
            # Format as percentages with 1 decimal place
            width <- paste0(format(value, nsmall = 1), "%")
            label <- paste0(format(value, nsmall = 1, decimal.mark = ",",digits = 1), "%")
            label <- ifelse(value<10, paste0("0", stringr::str_trim(label)), label)#pour gerer les valeurs à l'unite
            bar_chart(label, width = width, fill = "#FF8D7E", background = "#e1e1e1")
            },
          # And left-align the columns
          align = "left"
          ),
        espace_naturel = reactable::colDef(
          name = "Espaces naturels",
          cell = function(value) {
            # Format as percentages with 1 decimal place
            width <- paste0(format(value, nsmall = 1), "%")
            label <- paste0(format(value, nsmall = 1, decimal.mark = ",",digits = 1), "%")
            label <- ifelse(value<10, paste0("0", stringr::str_trim(label)), label)#pour gerer les valeurs à l'unite
            bar_chart(label, width = width, fill = "#169B62", background = "#e1e1e1")
            },
          # And left-align the columns
          align = "left"
          )
        )
      )

    css_header <- "font-family: Marianne;"
    css_caption <- "font-family: Marianne;text-align: right;"

    tableau_1_6_with_title <- htmlwidgets::prependContent(tableau_1_6,
                                                          htmltools::h2(style = css_header, "R\u00e9partition de l'occupation du sol"),
                                                          htmltools::p(style = css_header,glue::glue("Par d\u00e9partement et selon la population en {mois} {millesime_ocsge}"))
                                                          )
    tableau_1_6_with_caption <- htmlwidgets::appendContent(tableau_1_6_with_title,
                                                           htmltools::p(style = css_caption,glue::glue("Source : OCSGE {millesime_ocsge}"))
                                                           )
    return(tableau_1_6_with_caption)
    }

  if (code_reg  %notin% c('52')) {
    return(invisible(NULL))
    }

  }


