#!/usr/bin/env bash

set -e

THEME="${1:-catppuccin-mocha}"
CONFIG_DIR="$HOME/.config"
# WAYBAR_DIR="$CONFIG_DIR/niri/waybar-niri"

declare -A THEMES=(
  ["cat"]="catppuccin-mocha"
  ["rose"]="rose-pine-moon"
  ["dracula"]="dracula"
)

if [[ ! -v "THEMES[$THEME]" ]]; then
  echo "Unknown theme: $THEME"
  echo "Available themes: ${!THEMES[@]}"
  exit 1
fi

echo "Switching to theme: $THEME"

# Neovim
echo "vim.cmd.colorscheme('${THEMES[$THEME]}')" >"$CONFIG_DIR/nvim/lua/current_theme.lua"
echo "  ✓ Neovim"

# Kitty
if command -v kitty &>/dev/null && [[ -f "$CONFIG_DIR/kitty/themes/${THEME}.conf" ]]; then
  ln -sf "$CONFIG_DIR/kitty/themes/${THEME}.conf" "$CONFIG_DIR/kitty/current-theme.conf"
  kill -SIGUSR1 $(pgrep kitty) 2>/dev/null || true
  echo "  ✓ Kitty"
fi

# Btop
if [[ -f "$CONFIG_DIR/btop/themes/${THEME}.theme" ]]; then
  sed -i "s|^color_theme = .*|color_theme = \"$CONFIG_DIR/btop/themes/${THEME}.theme\"|" "$CONFIG_DIR/btop/btop.conf"
  echo "  ✓ Btop"
fi

# Yazi
if [[ -f "$CONFIG_DIR/yazi/themes/${THEME}.toml" ]]; then
  ln -sf "$CONFIG_DIR/yazi/themes/${THEME}.toml" "$CONFIG_DIR/yazi/theme.toml"
  echo "  ✓ Yazi"
fi

# # Waybar - simply copy the theme file to theme.css
# if [[ -f "$WAYBAR_DIR/themes/${THEME}.css" ]]; then
#     cp "$WAYBAR_DIR/themes/${THEME}.css" "$WAYBAR_DIR/theme.css"
#
#     pkill waybar 2>/dev/null || true
#     sleep 0.5
#     waybar -c "$WAYBAR_DIR/config.jsonc" -s "$WAYBAR_DIR/style.css" &
#     echo "  ✓ Waybar"
# else
#     echo "  ✗ Waybar: theme file not found at $WAYBAR_DIR/themes/${THEME}.css"
# fi

# Bat
if command -v bat &>/dev/null; then
  case $THEME in
  catppuccin-mocha) BAT_THEME="Catppuccin Mocha" ;;
  rose-pine-moon) BAT_THEME="TwoDark" ;;
  *) BAT_THEME="Monokai Extended" ;;
  esac

  if [[ -f "$CONFIG_DIR/bat/config" ]]; then
    sed -i "s/^--theme=.*/--theme=\"${BAT_THEME}\"/" "$CONFIG_DIR/bat/config"
  else
    mkdir -p "$CONFIG_DIR/bat"
    echo "--theme=\"${BAT_THEME}\"" >"$CONFIG_DIR/bat/config"
  fi
  echo "  ✓ Bat"
fi

echo ""
echo "✓ Theme switched to: $THEME"
