{ lib, config, pkgs, system, inputs , ... }:

with lib;
let
  cfg = config.modules.desktop.hypridle;
in {
  options.modules.desktop.hypridle = {
    enable = mkEnableOption "Enable hypridle, hyprland's idle daemon";
    package = mkOption {
      type = types.package;
      default = inputs.hypridle.packages.${system}.hypridle;
      example = "pkgs.hypridle";
    };
  };

  config = mkIf cfg.enable {
    hm.services.hypridle = let
      hyprctl = "${config.modules.desktop.hyprland.package}/bin/hyprctl";
    in {
      enable = true;
      package = cfg.package;

      lockCmd = "${pkgs.procps}/bin/pidof hyprlock || ${lib.getExe config.modules.desktop.hyprlock.package}";
      unlockCmd = "${pkgs.procps}/bin/pkill -USR1 hyprlock";

      beforeSleepCmd = "${pkgs.systemd}/bin/loginctl lock-session"; # lock the screen before sleeping
      afterSleepCmd = "${hyprctl} dispatch dpms on"; # turn on the screen to avoid moving mouse/pressing key

      listeners = [
        {
          timeout = 60 * 1;
          onTimeout = "${lib.getExe pkgs.brightnessctl} -c backlight -s set 20"; # dim screen, save brightness state
          onResume = "${lib.getExe pkgs.brightnessctl} -c backlight -r"; # restore previous screen brightness state
        }
        {
          timeout = 90; # 1.5 min
          onTimeout = "${hyprctl} dispatch dpms off"; # turn off screen
          onResume = "${hyprctl} dispatch dpms on"; # turn it back on
        }
        {
          timeout = 60 * 2; # 2 min
          onTimeout = "${pkgs.systemd}/bin/loginctl lock-session"; # lock computer
        }
        {
          timeout = 60 * 15; # 15 min
          onTimeout = "${pkgs.systemd}/bin/systemctl suspend"; # sleep/suspend
        }
      ];
    };
  };
}
