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

let
  cfg = config.services.tailscale-systray;
in
{
  meta.maintainers = [ lib.maintainers.yethal ];

  options.services.tailscale-systray = {
    enable = lib.mkEnableOption "Official Tailscale systray application for Linux";

    package = lib.mkPackageOption pkgs "tailscale" { };

    theme = lib.mkOption {
      type = lib.types.nullOr (
        lib.types.enum [
          "dark"
          "dark:nobg"
          "light"
          "light:nobg"
        ]
      );
      default = null;
      example = "dark:nobg";
      description = "Color theme to use for the Tailscale icon.";
    };
  };

  config = lib.mkIf cfg.enable {
    assertions = [
      (lib.hm.assertions.assertPlatform "services.tailscale-systray" pkgs lib.platforms.linux)
      {
        assertion = lib.versionAtLeast cfg.package.version "1.88.1";
        message = ''
          Tailscale systray is available since version 1.88.1
        '';
      }
      {
        assertion = cfg.theme != null -> lib.versionAtLeast cfg.package.version "1.98";
        message = ''
          Tailscale systray supports themes since version 1.98
        '';
      }
    ];

    systemd.user.services.tailscale-systray = {
      Unit = {
        Description = "Official Tailscale systray application for Linux";
        Requires = [ "tray.target" ];
        After = [
          "graphical-session.target"
          "tray.target"
        ];
        PartOf = [ "graphical-session.target" ];
      };
      Install = {
        WantedBy = [ "graphical-session.target" ];
      };
      Service.ExecStart = lib.concatStringsSep " " (
        [
          "${lib.getExe cfg.package} systray"
        ]
        ++ lib.optional (cfg.theme != null) "--theme ${cfg.theme}"
      );
    };
  };
}
