#!/usr/bin/env bash
# shellcheck shell=bash
#===============================================================================
# FILE: today
# USAGE: todo.sh today [OPTIONS]
# DESCRIPTION: Show overdue, today's, and tomorrow's high-priority tasks
# AUTHOR: Enhanced todo.sh action
# LICENSE: Same as todo.txt-cli
#===============================================================================

usage() {
    echo "    $(basename "$0") [OPTIONS]"
    echo "      Show overdue, today's, and tomorrow's high-priority tasks in columns"
    echo ""
    echo "    Options:"
    echo "      -n NUM        Max tomorrow items to show (1-3, default: 3)"
    echo "      -w WIDTH      Override terminal width"
    echo "      --plain       Disable colors"
    echo "      -h, --help    Show this help"
}

# Handle usage/help
if [[ "${1}" =~ (usage|help|--help) ]] || [[ "${2}" =~ (usage|help|--help) ]]; then
    usage
    exit
elif [[ "${1}" = "$(basename "$0")" ]]; then
    shift
fi

# Stop verbose output
export TODOTXT_VERBOSE=0

# Configuration
TOMORROW_LIMIT=3
TERM_WIDTH=0

# Simple argument parsing
while [[ $# -gt 0 ]]; do
    case $1 in
        -n)
            shift
            if [[ $# -gt 0 && "$1" =~ ^[1-3]$ ]]; then
                TOMORROW_LIMIT="$1"
            fi
            ;;
        -w)
            shift
            if [[ $# -gt 0 && "$1" =~ ^[0-9]+$ ]]; then
                TERM_WIDTH="$1"
            fi
            ;;
        --plain)
            export TODOTXT_PLAIN=1
            ;;
        -h|--help)
            usage
            exit 0
            ;;
    esac
    shift
done

# Get current dates
TODAY=$(date +%Y-%m-%d)
TOMORROW=$(date -v+1d +%Y-%m-%d 2>/dev/null || date -d "+1 day" +%Y-%m-%d 2>/dev/null || python3 -c "from datetime import date,timedelta; print((date.today()+timedelta(days=1)).isoformat())")

# Use todo.sh colors if available
if [[ -z "${TODOTXT_PLAIN:-}" ]]; then
    WHITE="${WHITE:-$'\033[1;37m'}"
    LIGHT_RED="${LIGHT_RED:-$'\033[1;31m'}"
    YELLOW="${YELLOW:-$'\033[1;33m'}"
    LIGHT_BLUE="${LIGHT_BLUE:-$'\033[1;34m'}"
    DARK_GREY="${DARK_GREY:-$'\033[1;30m'}"
    DEFAULT="${DEFAULT:-$'\033[0m'}"
else
    WHITE="" LIGHT_RED="" YELLOW="" LIGHT_BLUE="" DARK_GREY="" DEFAULT=""
fi

# Get terminal width for layout decision
if [[ $TERM_WIDTH -gt 0 ]]; then
    WIDTH=$TERM_WIDTH
elif [[ -n "${COLUMNS:-}" ]]; then
    WIDTH="$COLUMNS"
else
    WIDTH=$(tput cols 2>/dev/null || echo 80)
fi

# Collect tasks by category
echo "${WHITE}Today's Focus (${TODAY})${DEFAULT}"
echo "${DARK_GREY}$(printf '=%.0s' $(seq 1 $(( WIDTH > 50 ? 50 : WIDTH - 10 ))))${DEFAULT}"
echo

# Get all tasks with due dates and categorize
# Use todo.sh ls with specific terms to get properly colored output
OVERDUE_TASKS=$("${TODO_SH:-todo.sh}" ls | grep -E "due:[0-9]{4}-[0-9]{2}-[0-9]{2}" | awk -v today="$TODAY" '
    {
        if (match($0, /due:([0-9]{4}-[0-9]{2}-[0-9]{2})/)) {
            due_date = substr($0, RSTART+4, 10)
            if (due_date < today) print $0
        }
    }' | head -10)
    
TODAY_TASKS=$("${TODO_SH:-todo.sh}" ls "due:$TODAY")

TOMORROW_HI_TASKS=$("${TODO_SH:-todo.sh}" ls "due:$TOMORROW" | grep -E "^[^x][^[:space:]]*[[:space:]]*\([AB]\)" | head -n $TOMORROW_LIMIT)

# Display sections
if [[ $WIDTH -gt 120 ]]; then
    # Wide terminal - horizontal layout
    COL_WIDTH=$(( (WIDTH - 6) / 3 ))
    
    # Headers
    printf "${WHITE}%-${COL_WIDTH}s${DEFAULT} | ${WHITE}%-${COL_WIDTH}s${DEFAULT} | ${WHITE}%-${COL_WIDTH}s${DEFAULT}\n" \
        "OVERDUE" "TODAY" "TOMORROW (A/B)"
    
    printf "%-${COL_WIDTH}s-+-%-${COL_WIDTH}s-+-%-${COL_WIDTH}s\n" \
        "$(printf '%.0s-' $(seq 1 $COL_WIDTH))" \
        "$(printf '%.0s-' $(seq 1 $COL_WIDTH))" \
        "$(printf '%.0s-' $(seq 1 $COL_WIDTH))"
    
    # Convert to arrays for parallel processing
    readarray -t overdue_array <<< "$OVERDUE_TASKS"
    readarray -t today_array <<< "$TODAY_TASKS"
    readarray -t tomorrow_array <<< "$TOMORROW_HI_TASKS"
    
    # Find max rows
    MAX_ROWS=0
    [[ ${#overdue_array[@]} -gt $MAX_ROWS ]] && MAX_ROWS=${#overdue_array[@]}
    [[ ${#today_array[@]} -gt $MAX_ROWS ]] && MAX_ROWS=${#today_array[@]}
    [[ ${#tomorrow_array[@]} -gt $MAX_ROWS ]] && MAX_ROWS=${#tomorrow_array[@]}
    
    # Print rows
    for ((i=0; i<MAX_ROWS; i++)); do
        COL1="${overdue_array[i]:-}"
        COL2="${today_array[i]:-}"
        COL3="${tomorrow_array[i]:-}"
        
        # Truncate if too long
        [[ ${#COL1} -gt $((COL_WIDTH-2)) ]] && COL1="${COL1:0:$((COL_WIDTH-5))}..."
        [[ ${#COL2} -gt $((COL_WIDTH-2)) ]] && COL2="${COL2:0:$((COL_WIDTH-5))}..."
        [[ ${#COL3} -gt $((COL_WIDTH-2)) ]] && COL3="${COL3:0:$((COL_WIDTH-5))}..."
        
        printf "%-${COL_WIDTH}s | %-${COL_WIDTH}s | %-${COL_WIDTH}s\n" \
            "$COL1" "$COL2" "$COL3"
    done
    
else
    # Narrow terminal - vertical layout
    echo "${LIGHT_RED}📅 OVERDUE${DEFAULT}"
    if [[ -n "$OVERDUE_TASKS" ]]; then
        echo "$OVERDUE_TASKS" | head -5
    else
        echo "${DARK_GREY}  — none —${DEFAULT}"
    fi
    echo
    
    echo "${YELLOW}🎯 TODAY${DEFAULT}"
    if [[ -n "$TODAY_TASKS" ]]; then
        echo "$TODAY_TASKS"
    else
        echo "${DARK_GREY}  — none —${DEFAULT}"
    fi
    echo
    
    echo "${LIGHT_BLUE}⭐ TOMORROW (High Priority)${DEFAULT}"
    if [[ -n "$TOMORROW_HI_TASKS" ]]; then
        echo "$TOMORROW_HI_TASKS"
    else
        echo "${DARK_GREY}  — none —${DEFAULT}"
    fi
fi
