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

import { getBatteryIcon } from "@/lib/icons";
import { hideWindow } from "@lib/utils";

import PowerProfiles from "gi://AstalPowerProfiles?version=0.1";
import Battery from "gi://AstalBattery?version=0.1";
import Hyprland from "gi://AstalHyprland";

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

    const hypr = Hyprland.get_default();
    const power = PowerProfiles.get_default();
    const battery = Battery.get_default();

    const percentage = bind(battery, "percentage").as(p => Math.floor(p * 100));
    const charging = bind(battery, "charging");

    return <window
        visible={false}
        name={"battery_info"}
        monitor={bind(hypr, "focusedMonitor").as(monitor => monitor.id)}
        cssClasses={["battery_info"]}
        keymode={Astal.Keymode.EXCLUSIVE}
        exclusivity={Astal.Exclusivity.IGNORE}
        anchor={BOTTOM | LEFT | RIGHT}
        onKeyPressed={hideWindow}
        application={App}>
        <box halign={CENTER} cssClasses={["inner"]} spacing={10}>
            {percentage.as(p => <>
                <image
                    iconSize={Gtk.IconSize.LARGE}
                    iconName={getBatteryIcon(p, charging)}
                />

                <label cssClasses={["percentage"]}>{percentage.as(p => `${p}%`)}</label>
            </>)}

            {power.get_profiles().map(profile => <button
                label={profile.profile}
                cssClasses={bind(power, "active_profile").as(active =>
                    active === profile.profile
                        ? ["active"]
                        : []
                )}
                onClicked={() => power.set_active_profile(profile.profile)}
            />)}
        </box>
    </window>
}
