#!/bin/bash

# Bluetooth Management Script (Rofi-based)
# Dependencies: bluez, bluez-utils, rofi

SESSION_TYPE="$XDG_SESSION_TYPE"
ENABLED_COLOR="#81A1C1"
DISABLED_COLOR="#D35F5E"
CONNECTED_ICON="󰂄"
DISCONNECTED_ICON="󰂃"

get_status() {
    if bluetoothctl show | grep -q "Powered: yes"; then
        local status_icon=""
        local status_color=$ENABLED_COLOR
        # Check if any device is connected
        if bluetoothctl info | grep -q "Connected: yes"; then
            status_icon="󰂱"
        fi
    else
        local status_icon="󰂲"
        local status_color=$DISABLED_COLOR
    fi

    if [[ "$SESSION_TYPE" == "wayland" ]]; then
        echo "<span color=\"$status_color\">$status_icon</span>"
    else
        echo "%{F$status_color}$status_icon%{F-}"
    fi
}

manage_devices() {
    # Get paired devices
    local devices_list=$(bluetoothctl devices | awk '{print $3 " " $2}')
    if [ -z "$devices_list" ]; then
        notify-send "Bluetooth" "No paired devices found."
        return
    fi

    local chosen_device=$(echo -e "$devices_list" | rofi -dmenu -i -p "Bluetooth Devices: ")
    if [ -z "$chosen_device" ]; then return; fi

    local device_mac=$(echo "$chosen_device" | awk '{print $NF}')
    local device_name=$(echo "$chosen_device" | awk '{$NF=""; print $0}')

    # Check connection status
    local is_connected=$(bluetoothctl info "$device_mac" | grep "Connected: yes")

    if [ -n "$is_connected" ]; then
        action=$(echo -e "󰂲 Disconnect\n󰆴 Remove/Forget" | rofi -dmenu -p "Action for $device_name: ")
    else
        action=$(echo -e "󰂄 Connect\n󰆴 Remove/Forget" | rofi -dmenu -p "Action for $device_name: ")
    fi

    case $action in
        *"Connect")
            bluetoothctl connect "$device_mac" && notify-send "Bluetooth" "Connected to $device_name"
            ;;
        *"Disconnect")
            bluetoothctl disconnect "$device_mac" && notify-send "Bluetooth" "Disconnected from $device_name"
            ;;
        *"Remove"*)
            bluetoothctl remove "$device_mac" && notify-send "Bluetooth" "Removed $device_name"
            ;;
    esac
}

# Main Logic
if [[ "$1" == "--status" ]]; then
    get_status
    exit 0
fi

power_status=$(bluetoothctl show | grep "Powered: yes")
if [ -z "$power_status" ]; then
    toggle_label="󰂯 Enable Bluetooth"
    toggle_cmd="power on"
else
    toggle_label="󰂲 Disable Bluetooth"
    toggle_cmd="power off"
fi

chosen_option=$(echo -e "$toggle_label\n󰂱 Manage Devices\n󰘧 Scan for New Devices" | rofi -dmenu -p "Bluetooth: ")

case $chosen_option in
    *"Enable"*|*"Disable"*)
        bluetoothctl $toggle_cmd
        ;;
    *"Manage"*)
        manage_devices
        ;;
    *"Scan"*)
        notify-send "Bluetooth" "Scanning for 15 seconds..."
        bluetoothctl --timeout 15 scan on
        manage_devices
        ;;
esac
