# Species Summary Tab
tableize <- function(all_obs_data, nppsd_species_crosswalk) {
  transect_area <- x$transects %>%
    group_by(TripID, Transect) %>%
    summarize(
      area_sampled_km2 = sum(area_sampled_km2), 
      .groups = "drop"
    )

  all_table_data <- all_obs_data %>%
    filter(ONOFFTX == "ON") %>%
    mutate(Count = as.numeric(Count)) %>%
    rename(code = Species) %>%
    left_join(ref_species_codes, by = "code") %>%
    left_join(nppsd_species_crosswalk, by = c("code" = "custom_species_code")) %>%
    mutate(
      common_name = coalesce(common_name, custom_common_name)
    ) %>%
    group_by(TripID, Transect, code, common_name) %>%
    summarize(
      total = sum(Count, na.rm = TRUE),
      observations = n(),
      .groups = "drop"
    ) %>%
    inner_join(transect_area) %>%
    mutate(density = total / area_sampled_km2) %>%
    select(-area_sampled_km2) %>%
    arrange(TripID, Transect, desc(total), desc(observations))

  table_grouping <- all_table_data %>%
    transmute(table_grouping = paste(TripID, Transect, sep = "@")) %>%
    distinct() %>%
    pull(table_grouping)

  tables <- list()
  for (i in seq(1, length(table_grouping))) {
    tg <- table_grouping[i]
    trip_id <- str_trim(gsub("([^@]+)@([^@]+)", "\\1", tg))
    tx_number <- str_trim(gsub("([^@]+)@([^@]+)", "\\2", tg))
    table_data <- all_table_data %>%
      filter(
        TripID == trip_id,
        Transect == tx_number
      )
    tables[[as.character(i)]] <-
      kable(table_data,
        caption = paste(trip_id, tx_number, sep = " "),
        format = "html", include.rownames = FALSE,
        table.attr = 'class="data table table-bordered table-condensed"',
        caption.placement = "top"
      )
  }

  off_transect_data <- all_obs_data %>%
    filter(ONOFFTX == "OFF") %>%
    mutate(Count = as.numeric(Count)) %>%
    rename(code = Species) %>%
    left_join(ref_species_codes, by = "code") %>%
    left_join(nppsd_species_crosswalk, by = c("code" = "custom_species_code")) %>%
    mutate(
      common_name = coalesce(common_name, custom_common_name)
    ) %>%
    group_by(code, common_name) %>%
    summarize(
      total = sum(Count, na.rm = TRUE),
      observations = n(),
      density = as.numeric(NA),
      .groups = "drop"
    ) %>%
    arrange(desc(total), desc(observations))

  tables[[as.character(length(table_grouping) + 1)]] <-
    kable(off_transect_data,
      caption = "off transect",
      format = "html", include.rownames = FALSE,
      table.attr = 'class="data table table-bordered table-condensed"',
      caption.placement = "top"
    )

  return(lapply(tables, paste))
}

output$spp_summary <- renderUI({
  out <- unlist(tableize(x$all_obs_data, x$nppsd_species_crosswalk))

  return(div(HTML(out), class = "shiny-html-output"))
})

output$dl_spp_summary <- downloadHandler(
  filename = paste0("species_summary_", date(now()), ".csv"),
  content = function(file) {
    transect_area <- x$transects %>%
      group_by(TripID, Transect) %>%
      summarize(
        area_sampled_km2 = sum(area_sampled_km2), 
        .groups = "drop"
      )

    all_table_data <- x$all_obs_data %>%
      filter(ONOFFTX == "ON") %>%
      mutate(Count = as.numeric(Count)) %>%
      rename(code = Species) %>%
      left_join(ref_species_codes, by = "code") %>%
      left_join(x$nppsd_species_crosswalk, by = c("code" = "custom_species_code")) %>%
      mutate(
        common_name = coalesce(common_name, custom_common_name)
      ) %>%
      group_by(TripID, Transect, code, common_name) %>%
      summarize(
        total = sum(Count, na.rm = TRUE),
        observations = n(),
        .groups = "drop"
      ) %>%
      inner_join(transect_area) %>%
      mutate(density = total / area_sampled_km2) %>%
      select(-area_sampled_km2) %>%
      arrange(TripID, Transect, desc(total), desc(observations))

    off_transect_data <- x$all_obs_data %>%
      filter(ONOFFTX == "OFF") %>%
      mutate(Count = as.numeric(Count)) %>%
      rename(code = Species) %>%
      left_join(ref_species_codes, by = "code") %>%
      left_join(x$nppsd_species_crosswalk, by = c("code" = "custom_species_code")) %>%
      mutate(
        common_name = coalesce(common_name, custom_common_name)
      ) %>%
      group_by(code, common_name) %>%
      summarize(
        total = sum(Count, na.rm = TRUE),
        observations = n(),
        density = as.numeric(NA),
        .groups = "drop"
      ) %>%
      mutate(
        TripID = NA_character_,
        Transect = "off transect"
      ) %>%
      arrange(desc(total), desc(observations))

    write_csv(
      bind_rows(all_table_data, off_transect_data),
      file,
      na = ""
    )
  }
)
