#!/bin/sh
#
# gun - saves a quick note to markdown file `$QUICKNOTE_PATH`
# dependencies: gum | prettier (optional)

if ! command -v gum >/dev/null 2>&1; then
  printf '%s\n' "${0##*/}: gum not found in PATH!" >&2
  exit 1
fi

fg="#f5e0dc"
bg="#1e1e2e"
border_fg="#cba6f7"

prompt_fg="#f2cdcd"
cursor_fg="#cba6f7"
timestamp=$(date +"%Y-%m-%d at %I:%M:%S %p")
today=$(date +"%Y-%m-%d")

gum style \
  --foreground "${fg}" \
  --background "${bg}" \
  --border-foreground "${border_fg}" \
  --border double \
  --align center \
  --width 60 \
  --padding "0 6" \
  --margin "1 0" \
  "➕   Quick Note ➕"

topic=$(gum input \
  --placeholder "Topic for your note" \
  --prompt.foreground "${prompt_fg}" \
  --cursor.foreground "${cursor_fg}" \
  --width 50)

topic=${topic:-Quickie}

# WARN: ctrl + j is binded in tmux. so changing line doesn't work
description=$(gum write \
  --placeholder "Write your quick note here..." \
  --prompt.foreground "${prompt_fg}" \
  --cursor.foreground "${cursor_fg}" \
  --cursor.mode="blink" \
  --width 70 \
  --height 3)

description=${description:-${topic}}

# shellcheck disable=SC2250
markdown_note=$(
  cat <<EOF
---

## $topic

󰥔  **$timestamp**

$description
EOF
)

outputHeading() {
  gum style --bold --foreground "${border_fg}" "$1"
}

# shellcheck disable=SC2312
echo "$(outputHeading Topic): ${topic}"
# shellcheck disable=SC2312
echo "$(outputHeading Time): ${timestamp}"
# shellcheck disable=SC2312
echo "$(outputHeading Description):"
echo "${description}"

# shellcheck disable=SC2015
gum confirm "Save Note?" \
  && echo "${markdown_note}" >>"${QUICKNOTE_PATH:-${PWD}}/${today}.md" \
  && gum style \
    --border double \
    --padding "0 4" \
    --margin "1 0" \
    --width 60 \
    --align center \
    --foreground "#a6e3a1" \
    --border-foreground "${border_fg}" \
    "  Note saved" \
  || gum style \
    --border double \
    --padding "0 4" \
    --margin "1 0" \
    --width 60 \
    --align center \
    --foreground "#f38ba8" \
    --border-foreground "${border_fg}" \
    "  Note cancelled"

if command -v prettier >/dev/null; then
  prettier "${QUICKNOTE_PATH:-${PWD}}" -w --log-level silent
fi
