{
  pkgs,
  config,
  lib,
  ...
}:
with lib;
let
  cfg = config.eboskma.programs.polybar;

  colors = {
    background = "#cc000000";
    foreground = "#ffffffff";
    urgent = "#c9545d";
  };

  polybar-playerctl =
    let
      pythonWithPackages = pkgs.python3.withPackages (pythonPackages: [ pythonPackages.pygobject3 ]);
    in
    pkgs.stdenv.mkDerivation {
      name = "polybar-playerctl";
      buildInputs = [
        pythonWithPackages
        pkgs.playerctl
      ];
      propagatedBuildInputs = [
        pythonWithPackages
        pkgs.python3Packages.pygobject3
        pkgs.playerctl
      ];
      nativeBuildInputs = [
        pkgs.gobject-introspection
        pkgs.wrapGAppsHook
      ];

      strictDeps = false;
      dontUnpack = true;
      installPhase = ''
        mkdir -p $out/bin
        cp ${./scripts/polybar-playerctl} $out/bin/polybar-playerctl
        chmod +x $out/bin/polybar-playerctl
      '';
    };

  headset-battery = pkgs.writeShellScript "headset-battery" ''
    battery_level=$(${pkgs.headsetcontrol}/bin/headsetcontrol -c -b 2> /dev/null)

    if [[ $? -ne 0 ]]; then
      printf "󰂑"
      exit
    fi

    battery_icons=(󰁺 󰁻 󰁼 󰁽 󰁾 󰁿 󰂀 󰂁 󰂂 󰁹 )
    battery_charging="󰂄"

    if [[ "''${battery_level}" -eq -1 ]]; then
      printf "%s " "''${battery_charging}"
    else
      idx=$(((battery_level / 10)))
      if [[ "''${idx}" -eq 10 ]]; then
        idx=9
      fi

      battery_icon="''${battery_icons[''${idx}]}"
      printf "%s %i%%" "''${battery_icon}" "''${battery_level}"
    fi
  '';
in
{
  options.eboskma.programs.polybar = {
    enable = mkEnableOption "activate polybar";
  };

  config = mkIf cfg.enable {
    # systemd.user.services.polybar = {
    #   Install = { WantedBy = [ "graphical-session.target" ]; };
    # };

    services.polybar = {
      enable = true;

      package = pkgs.polybarFull.override {
        i3Support = true;
        pulseSupport = true;
        mpdSupport = true;
      };

      script = ''
        ${pkgs.polybar}/bin/polybar-msg cmd quit
        while ${pkgs.procps}/bin/pgrep -u ''${UID} -x polybar > /dev/null; do sleep 0.1; done

        outputs=$(${pkgs.polybar}/bin/polybar -m | ${pkgs.gnugrep}/bin/grep -v primary | ${pkgs.coreutils}/bin/cut -d ':' -f 1)
        primary=$(${pkgs.polybar}/bin/polybar -m | ${pkgs.gnugrep}/bin/grep primary | ${pkgs.coreutils}/bin/cut -d ':' -f 1)

        MONITOR=''${primary} polybar -q main & disown

        sleep 0.5 # Make sure the primary bar is started so the tray appears here

        for m in ''${outputs}; do
          MONITOR=''${m} polybar -q main & disown
        done
      '';

      settings = {
        "global/wm" = {
          margin.bottom = 0;
          margin.top = 0;
        };

        "bar/main" = {
          monitor = "\${env:MONITOR:DP-0}";
          fixed.center = true;
          width = "100%";
          height = 48;
          # offset.x = "1%";
          # offset.y = "2%";
          offset.x = 0;
          offset.y = 0;
          background = "${colors.background}";
          foreground = "${colors.foreground}";
          line.size = 2;

          font = [
            "Iosevka Nerd Font:style=Bold:size=16;2"
            "Iosevka Nerd Font:size=18;3"
            "Iosevka Nerd Font:size=20;4"
          ];

          modules = {
            left = "workspaces playerctl";
            center = "date";
            right = "headset-battery memory cpu pulseaudio network";
          };

          dim.value = 0.8;

          tray = {
            position = "right";
            detached = false;
            maxsize = 24;
            background = "${colors.background}";
            offset.x = 0;
            offset.y = 0;
            padding = 0;
            scale = 1.0;
          };

          enable.ipc = true;

          cursor = {
            click = "pointer";
          };
        };

        settings = {
          screenchange.reload = false;
          throttle.output.text = 5;
          throttle.output.for = 10;

          compositing = {
            background = "source";
            foreground = "over";
            overline = "over";
            underline = "over";
            border = "over";
          };

          pseudo.transparency = false;
        };

        "module/workspaces" = {
          type = "internal/i3";
          pin.workspaces = true;
          strip.wsnumbers = true;
          enable.click = true;
          enable.scroll = true;

          format = "<label-state> <label-mode>";

          label = {
            mode = {
              text = "󰁌 %mode%"; # Icon: arrow_expand_all
              padding = 1;
            };

            focused = {
              text = " %index%"; # Icon: fa-circle
              padding = 1;
              background = "#333333";
              underline = "#ffffff";
            };

            unfocused = {
              text = " %index%"; # Icon: fa-circle_o
              padding = 1;
            };

            visible = {
              text = " %index%"; # Icon: fa-dot_circle_o
              padding = 1;
            };

            urgent = {
              text = " %index%"; # Icon: fa-exclamation_circle
              background = "${colors.urgent}";
              padding = 1;
            };
          };
        };

        "module/playerctl" = {
          type = "custom/script";
          exec = "${polybar-playerctl}/bin/polybar-playerctl";
          interval = 1;
          click = {
            left = "${polybar-playerctl}/bin/polybar-playerctl play-pause";
            middle = "${polybar-playerctl}/bin/polybar-playerctl next";
            right = "${polybar-playerctl}/bin/polybar-playerctl prevous";
          };
          format.padding = 2;

          scroll.up = "${polybar-playerctl}/bin/polybar-playerctl next-player";
        };

        "module/date" = {
          type = "internal/date";
          interval = 1.0;
          time = {
            text = " %H:%M:%S";
            alt = " %a, %d %b %Y";
          };

          format = {
            text = "<label>";
            padding = 2;
          };

          label.text = "%time%";
        };

        "module/headset-battery" = {
          type = "custom/script";
          exec = "${headset-battery}";
          interval = 1;

          format = {
            prefix = "󰋎 "; # Icon: headset
            padding = 2;
          };

          label.text = "%output%";

          click = {
            left = "${pkgs.headsetcontrol}/bin/headsetcontrol -s 128";
            right = "${pkgs.headsetcontrol}/bin/headsetcontrol -s 0";
          };
        };

        "module/memory" = {
          type = "internal/memory";
          interval = 1;

          format = {
            text = "<label>";
            prefix = "󰍛 "; # Icon: memory
            padding = 2;
          };

          label.text = "%mb_used% (%percentage_used%%)";
        };

        "module/cpu" = {
          type = "internal/cpu";
          interval = 1;

          format = {
            text = "<label>";
            prefix = "󰻠 "; # Icon: cpu_64_bit
            padding = 2;
          };

          label = "%percentage:3%%";
        };

        "module/pulseaudio" = {
          type = "internal/pulseaudio";
          interval = 5;

          use.ui.max = false;

          format = {
            volume = {
              text = "<ramp-volume> <label-volume>";
              padding = 2;
            };

            muted = {
              text = "<label-muted>";
              prefix = "󰖁"; # Icon: volume_off
              background = "${colors.urgent}";
              padding = 2;
            };
          };

          label = {
            volume.text = "%percentage%%";

            muted.text = " Muted";
          };

          ramp.volume = [
            "󰕿"
            "󰖀"
            "󰕾"
          ]; # Icons: volume_low volume_medium volume_high

          click.right = "${pkgs.pavucontrol}/bin/pavucontrol";
        };

        "module/network" = {
          type = "internal/network";
          interval = 1;

          interface = "enp4s0";

          click-left = "${pkgs.networkmanagerapplet}/bin/nm-connection-editor";

          accumulate.stats = true;
          unknown.as.up = true;

          format = {
            connected = {
              text = "<label-connected>";
              padding = 2;
            };

            disconnected = {
              text = "<label-disconnected>";
              padding = 2;
            };

            packetloss.text = "<animation-packetloss> <label-connected>";
          };

          label = {
            connected.text = "󰈀 %local_ip%  %upspeed:9%  %downspeed:9%"; # Icon: ethernet
            disconnected.text = "󰲜 %{A1:networkmanager_dmenu &:} Offline%{A}"; # Icon: network_off_outline
          };

          animation = {
            packetloss.text = [
              {
                text = "⚠";
                foreground = "${colors.urgent}";
              }
              {
                text = "⚠";
                foreground = "${colors.foreground}";
              }
            ];
            packetloss.framerate = 500;
          };
        };
      };
    };
  };
}