import { App, Astal, Gdk, Gtk } from "astal/gtk4"
import { bind, Binding } from "astal"

import PowerProfiles from "gi://AstalPowerProfiles";
import Battery from "gi://AstalBattery";

import DateTime from "@lib/widgets/datetime";
import Workspace from "./workspace";
import TrayView from "./tray";

type Substitution = { charging?: string, idle?: string }

const getBatteryIcon = (percentage: number, charging: Binding<boolean>) => {
    const levels = Array.from({ length: 10 }, (_, i) => (i + 1) * 10);
    const level = levels.find((level) => percentage <= level)!;

    const substitutions: Record<number, Substitution> = {
        100: { charging: "battery-level-100-charged-symbolic" }
    };

    return charging.as(c => c
        ? substitutions[level]?.charging || `battery-level-${level}-charging-symbolic`
        : substitutions[level]?.idle || `battery-level-${level}-symbolic`
    );
};

const BatteryInfo = ({ battery }: { battery: Battery.Device }) => {
    const percentage = bind(battery, "percentage").as(p => Math.floor(p * 100));
    const charging = bind(battery, "charging");
    const power = PowerProfiles.get_default();

    return (
        <box>
            {percentage.as(p => <button
                hasFrame={false}
                tooltipText={bind(power, "active_profile")}
            >
                <box>
                    <label>{percentage.as(p => `${p}%`)}</label>
                    <image iconName={getBatteryIcon(p, charging)} />
                </box>
            </button>)}
        </box>
    );
};

export default function Bar(monitor_id: number) {
    const { BOTTOM, LEFT, RIGHT } = Astal.WindowAnchor
    const CENTER = Gtk.Align.CENTER;

    const battery = Battery.get_default();

    const openQuickSettings = (_self: Gtk.Button, state: Gdk.ButtonEvent) => {
        if (state.get_button() === Gdk.BUTTON_PRIMARY)
            App.get_window("quick_settings")?.show()
    }

    return <window
        visible
		name={`bar_${monitor_id}`}
		monitor={monitor_id}
        cssClasses={["bar"]}
        exclusivity={Astal.Exclusivity.EXCLUSIVE}
        anchor={BOTTOM | LEFT | RIGHT}
        application={App}>
        <box halign={CENTER} cssClasses={["inner"]}>
            {[
                Workspace(),
                <menubutton hasFrame={false}>
                    <DateTime format="%d.%m.%Y %H:%M:%S" interval={1000} />
                    <popover>
                        <Gtk.Calendar />
                    </popover>
                </menubutton>,
                BatteryInfo({ battery }),
                <button hasFrame={false} iconName={"applications-system-symbolic"} onButtonPressed={openQuickSettings} />,
                TrayView()
            ]}
        </box>
    </window>
}
