#!/usr/bin/env bash

module_description() {
  printf "Apply Theme - select and apply a Hyprland theme\n"
}

module_required() { return 1; }
module_should_skip() { return 1; }

module_prereqs() {
  return 0
}

module_main() {
  log_section "Theme Application"

  local theme_script="$HOME/.config/hypr/Scripts/theme-menu.sh"
  local themes_dir="$HOME/.config/hypr/Themes"

  if [[ ! -f "$theme_script" ]]; then
    log_warn "Theme script not found (dotfiles may not be deployed yet)"
    return 1
  fi

  local theme_files=()
  mapfile -t theme_files < <(find "$themes_dir" -name '*.theme' -type f | sort 2>/dev/null)

  if ((${#theme_files[@]} == 0)); then
    log_warn "No theme files found in $themes_dir"
    return 1
  fi

  local theme_names=()
  local file
  for file in "${theme_files[@]}"; do
    theme_names+=("$(basename "$file" .theme)")
  done

  tui_bold "Available themes:"
  local i
  for i in "${!theme_names[@]}"; do
    tui_info "[$i] ${theme_names[$i]}"
  done
  printf '\n'

  local choice
  if ((${#theme_files[@]} == 1)); then
    tui_info "Only one theme available, auto-selecting: ${theme_names[0]}"
    choice="${theme_files[0]}"
  else
    choice="$(
      local labels=()
      for name in "${theme_names[@]}"; do
        labels+=("$name")
      done
      tui_choose "Select a theme" "${labels[@]}"
    )"
    if [[ -z "$choice" ]]; then
      log_info "No theme selected, skipping"
      return 0
    fi
    local idx
    for idx in "${!theme_names[@]}"; do
      if [[ "$choice" == "${theme_names[$idx]}" ]]; then
        choice="${theme_files[$idx]}"
        break
      fi
    done
  fi

  if [[ -z "$choice" || ! -f "$choice" ]]; then
    log_warn "Invalid theme selection"
    return 1
  fi

  log_info "Selected theme: $(basename "$choice" .theme)"

  if ! tui_confirm "Apply theme: $(basename "$choice" .theme)?"; then
    log_info "Theme application skipped"
    return 0
  fi

  sudo_run mkdir -p /var/lib/pascal-sddm-theme 2>/dev/null || true
  sudo_run chown "$(id -u):$(id -g)" /var/lib/pascal-sddm-theme 2>/dev/null || true

  log_info "Applying theme..."
  if ! tui_spin "Applying theme..." bash "$theme_script" --apply "$choice"; then
    log_warn "Theme application returned errors"
    return 1
  fi

  log_success "Theme applied: $(basename "$choice" .theme)"
}
