import { App, Astal, Gtk, Gdk } from "astal/gtk4";
import { Variable, GLib, bind } from "astal";
import Battery from "gi://AstalBattery";
import Wp from "gi://AstalWp";
import Network from "gi://AstalNetwork";
import { Workspaces } from "./Workspaces";

function Wifi() {
  const network = Network.get_default();
  const wifi = bind(network, "wifi");

  return (
    <box visible={wifi.as(Boolean)}>
      {wifi.as(
        (wifi) =>
          wifi && (
            <image cssClasses={["Wifi"]} iconName={bind(wifi, "iconName")} />
          ),
      )}
    </box>
  );
}

function Audio() {
  const speaker = Wp.get_default()?.audio.defaultSpeaker!;

  return (
    <box cssClasses={["AudioSlider"]}>
      <image iconName={bind(speaker, "volumeIcon")} />
    </box>
  );
}

function BatteryLevel() {
  const bat = Battery.get_default();

  return (
    <box cssClasses={["Battery"]} visible={bind(bat, "isPresent")}>
      <image iconName={bind(bat, "batteryIconName")} />
      <label
        label={bind(bat, "percentage").as((p) => `${Math.floor(p * 100)} %`)}
      />
    </box>
  );
}

function Time({ format = "%H:%M - %A %e." }) {
  const time = Variable<string>("").poll(
    1000,
    () => GLib.DateTime.new_now_local().format(format)!,
  );

  return (
    <label cssClasses={["Time"]} onDestroy={() => time.drop()} label={time()} />
  );
}

export default function Bar(monitor: Gdk.Monitor) {
  const { TOP, LEFT, RIGHT } = Astal.WindowAnchor;

  return (
    <window
      visible
      namespace={"bar"}
      cssClasses={["Bar"]}
      gdkmonitor={monitor}
      exclusivity={Astal.Exclusivity.EXCLUSIVE}
      anchor={TOP | LEFT | RIGHT}
    >
      <centerbox>
        <box hexpand halign={Gtk.Align.START}>
          <Workspaces />
        </box>
        <box>
          <Time />
        </box>
        <box cssClasses={["NotificationCenter"]} hexpand halign={Gtk.Align.END}>
          <Audio />
          <Wifi />
          <BatteryLevel />
        </box>
      </centerbox>
    </window>
  );
}
