{ nixosConfig
, config
, pkgs
, lib
, ...
}:
with nixosConfig.nix-rice.lib;
let
  inherit (nixosConfig.nix-rice.rice) colorPalette opacity;
  alpha = 255 * opacity;
  grep = "${pkgs.gnugrep}/bin/grep";
  cut = "${pkgs.coreutils}/bin/cut";
  pavucontrol = "${pkgs.pavucontrol}/bin/pavucontrol";
  pgrep = "${pkgs.procps}/bin/pgrep";
  pkill = "${pkgs.procps}/bin/pkill";
  playerCtl = "${pkgs.playerctl}/bin/playerctl";
  dunstctl = "${pkgs.dunst}/bin/dunstctl";
  zscroll = "${pkgs.zscroll}/bin/zscroll";
  notificationStatus = pkgs.writeShellScript "notificationStatus" ''
    PATH=$PATH:"${lib.makeBinPath [ pkgs.dbus ]}"
    if [[ `${dunstctl} is-paused` == "true" ]]; then echo 󰂛; else echo 󰂚; fi
  '';
  notificationToggle = pkgs.writeShellScript "notificationToggle" ''
    PATH=$PATH:"${lib.makeBinPath [ pkgs.dbus ]}"
    ${dunstctl} set-paused toggle
  '';
  keyboardStatus = pkgs.writeShellScript "keyboardStatus" ''
    PATH=$PATH:"${lib.makeBinPath [ pkgs.coreutils ]}"
    STATE=~/.local/share/keyboard-switch.state
    touch $STATE
    if [[ `cat $STATE` == "disabled" ]]; then echo 󰌐; else echo 󰌌; fi
  '';
  keyboardToggle = pkgs.writeShellScript "keyboardToggle" ''
    PATH=$PATH:"${lib.makeBinPath [ pkgs.keyboard-switch ]}"
    keyboard-switch
  '';
  notificationHistory = pkgs.writeShellScript "notificationToggle" ''
    PATH=$PATH:"${lib.makeBinPath [ pkgs.dbus ]}"
    ${dunstctl} set-paused false
    for i in {1..10}; do ${dunstctl} history-pop; done
  '';
  playerStatusBasic = pkgs.writeShellScript "playerStatusBasic" ''
    ${playerCtl} status || true
  '';
  playerStatusSrc = pkgs.writeShellScript "playerStatusSrc" ''
    ${playerCtl} -f '{{title}} - {{artist}}' metadata || true
  '';
  playerStatus = pkgs.writeShellScript "playerStatus" ''
    ${zscroll} -l 25 -M ${playerStatusBasic} \
      -m "Playing" "-b '▶ ' -s 1" \
      -m "Paused" "-b '⏸ ' -s 0" \
      -u true ${playerStatusSrc} &
    wait
  '';
  powermenu = pkgs.writeShellScript "powermenu" ''
    PATH=$PATH:"${
      lib.makeBinPath [
        pkgs.rofi
        pkgs.rofi-power-menu
        pkgs.zsh
      ]
    }"
    zsh -c 'rofi -show menu -modi "menu:rofi-power-menu --choices=shutdown/reboot/hibernate/logout"'
  '';
  colors = palette.toARGBHex rec {
    normal = {
      foreground = color.darken 10 colorPalette.foreground;
      background = color.setAlphaRgba alpha colorPalette.background;
      underline = colorPalette.normal.blue;
    };

    active = {
      inherit (colorPalette) foreground;
      background = color.setAlphaRgba alpha colorPalette.background;
      underline = colorPalette.normal.yellow;
    };

    selected = {
      inherit (colorPalette) foreground;
      background = color.setAlphaRgba alpha colorPalette.background;
      underline = colorPalette.bright.red;
    };

    inherit (colorPalette.normal) green red yellow;
    inherit (color) transparent;
    orange = colorPalette.bright.red;
    alert = orange;
  };

  commonBar = {
    locale = config.home.language.base;
    monitor = "\${env:MONITOR}";
    width = "100%";
    height = 20;
    radius = 6.0;
    fixed-center = false;

    inherit (colors.normal) background foreground;

    line-size = 2;
    line-color = colors.normal.underline;
    padding = 0;
    module.margin = 0;
    separator = " ";
    border = {
      color = colors.transparent;
      left.size = 2;
      righ.sizet = 2;
      top.size = 2;
      bottom.size = 0;
    };
    font = [
      "${rice.font.monospace.name}:size=${toString rice.font.monospace.size};2"
      # "Font Awesome 6 Free:size=14;0"
      # "Noto Color Emoji:size=2;2"
      "Noto Sans Symbols2:size=${toString rice.font.monospace.size};2"
      "Material Design Icons:size=${toString rice.font.monospace.size};2"
      # "EmojiOne Color:size=${toString rice.font.monospace.size};0"
      "Noto Sans CJK JP:size=${toString rice.font.monospace.size};0"
      "Noto Sans CJK KR:size=${toString rice.font.monospace.size};0"
      "Noto Sans CJK CN:size=${toString rice.font.monospace.size};0"
      "Noto Sans CJK HK:size=${toString rice.font.monospace.size};0"
    ];
    enable-ipc = true;
    wm-restack = "bspwm";
  };

  ramp = [ "▂" "▃" "▄" "▅" "▆" "▇" ];
in
{
  home.packages = builtins.attrValues {
    inherit (pkgs) noto-fonts material-design-icons noto-fonts-cjk-sans;
    # emojione
    # noto-fonts-emoji
    # font-awesome
    inherit (rice.font.monospace) package;
  };
  services.polybar = {
    enable = true;
    package = pkgs.polybarFull;
    script = ''
      monitor=`polybar -m | ${grep} primary | ${cut} -d":" -f1`
      MONITOR=$monitor polybar primary &
      monitors=(`polybar -m | ${grep} -v primary | ${cut} -d":" -f1`)
      for monitor in "''${monitors[@]}"; do
        MONITOR=$monitor polybar secondary &
      done
    '';

    settings = {
      "settings" = {
        screenchange-reload = false;
      };

      "bar/primary" = lib.recursiveUpdate commonBar {
        modules-left = "bspwm";
        # modules-center =
        modules-right = "player pulseaudio temperature cpu memory battery keyboard-switch notifications powermenu date";
        tray = {
          position = "right";
          padding = 1;
        };
      };

      "bar/secondary" = lib.recursiveUpdate commonBar {
        modules-left = "bspwm";
        # modules-center =
        modules-right = "player pulseaudio temperature cpu memory battery keyboard-switch notifications powermenu date";
      };

      "module/battery" = {
        type = "internal/battery";

        adapter = "AC";
        battery = "BAT0";
        full.at = 98;

        animation = {
          charging = {
            text = [
              ""
              ""
              ""
              ""
              ""
            ];
            framerate = "750";
          };
          discharging = {
            text = [
              ""
              ""
              ""
              ""
              ""
            ];
            framerate = "750";
          };
        };

        format = {
          charging = lib.recursiveUpdate colors.selected { text = "<animation-charging> <label-charging>"; };
          discharging = lib.recursiveUpdate colors.active {
            text = "<animation-discharging> <label-discharging>";
          };
          full = lib.recursiveUpdate colors.normal { text = " <label-full>"; };
        };

        label.text = "%percentage%%";
        #   = {
        #   chargin = "%percentage%%";
        #   dischargin = "%percentage%%";
        #   full = "%percentage%%";
        # };
      };

      "module/bspwm" = {
        type = "internal/bspwm";
        format = "<label-state>";

        label =
          let
            common = {
              padding = 1;
              # separator = " ";
              text = "%name%";
            };
          in
          {
            focused = lib.recursiveUpdate common colors.selected;
            occupied = lib.recursiveUpdate common colors.active;
            urgent = lib.recursiveUpdate (lib.recursiveUpdate common colors.active) {
              background = colors.alert;
            };
            empty = lib.recursiveUpdate common colors.normal;
          };
      };

      "module/cpu" = {
        type = "internal/cpu";
        format = lib.recursiveUpdate colors.normal { text = " <label>"; };
        interval = 2;
        label = "%percentage-sum%%";
        ramp-load = ramp;
      };

      "module/date" = {
        type = "internal/date";
        format = colors.normal;
        date = {
          alt = "%Y-%m-%d";
          text = "%a %d/%m/%y";
        };
        interval = "1";
        label = "%date% %time%";
        time = {
          alt = "%H:%M:%S";
          text = "%H:%M";
        };
      };

      "module/memory" = {
        type = "internal/memory";
        format = lib.recursiveUpdate colors.normal { text = " <label>"; };
        interval = 2;
        label = "%percentage_used%%";
        ramp-used = ramp;
      };

      "module/pulseaudio" = {
        interval = 2;
        bar.volume = {
          empty = {
            text = "─";
          };
          fill = {
            text = "─";
          };
          indicator = {
            text = "|";
          };
          width = "10";
          foreground = [
            colors.green
            colors.green
            colors.green
            colors.green
            colors.green
            colors.yellow
            colors.orange
            colors.red
          ];
        };
        click.right = "${pgrep} pavucontrol && ${pkill} pavucontrol || ${pavucontrol}";
        format = {
          padding = 1;
          muted = colors.active;
          volume = lib.recursiveUpdate colors.normal { text = "<ramp-volume> <label-volume>"; };
        };
        label.muted.text = "󰝟 muted";
        label.volume.text = "%percentage%%";
        ramp.volume = [
          "󰕿"
          "󰖀"
          "󰕾"
        ];
        type = "internal/pulseaudio";
      };

      "module/temperature" = {
        format = lib.recursiveUpdate colors.normal {
          text = "<ramp> <label>";
          warn = {
            text = "<ramp> <label-warn>";
            underline = colors.alert;
          };
        };
        label = {
          text = "%temperature-c%";
          warn = "%temperature-c%";
        };
        ramp.text = [
          ""
          ""
          ""
          ""
          ""
        ];
        thermal.zone = if nixosConfig.networking.hostName == "odin" then 8 else 0;
        type = "internal/temperature";
        warn.temperature = "90";
      };
      "module/powermenu" = {
        type = "custom/script";
        format = lib.recursiveUpdate colors.normal { padding = 0; };
        exec = "echo ";
        click.left = "${powermenu}";
      };
      "module/notifications" = {
        type = "custom/script";
        format = lib.recursiveUpdate colors.normal { padding = 0; };
        exec = "${notificationStatus}";
        click.left = "${notificationToggle}";
        click.right = "${notificationHistory}";
        interval = 0.5;
        # tail = 1;
      };
      "module/keyboard-switch" = {
        type = "custom/script";
        format = lib.recursiveUpdate colors.normal { padding = 0; };
        exec = "${keyboardStatus}";
        click.left = "${keyboardToggle}";
        interval = 1;
        # tail = 1;
      };
      "module/player" = {
        type = "custom/script";
        format = colors.normal;
        exec = playerStatus;
        tail = true;
        click.left = "${playerCtl} play-pause";
        clicl.right = "${playerCtl} stop";
        scroll = {
          up = "${playerCtl} previous";
          down = "${playerCtl} next";
        };
      };
      "module/player-prev" = {
        type = "custom/script";
        format = colors.normal;
        exec = "echo 󰒮";
        click.left = "${playerCtl} previous";
      };
      "module/player-next" = {
        type = "custom/script";
        format = colors.normal;
        exec = "echo 󰒭";
        click.left = "${playerCtl} next";
      };
      "module/player-play-pause" = {
        type = "custom/script";
        format = colors.normal;
        exec = "echo 󰐎";
        click.left = "${playerCtl} play-pause";
      };
    };
  };
}
