{
  lib,
  pkgs,
  config,
  ...
}:
let
  inherit (lib)
    mkEnableOption
    mkOption
    mkIf
    flatten
    map
    filter
    any
    ;
  inherit (lib.types)
    listOf
    package
    bool
    str
    ;

  cfg = config.modules.media;
  mkMedia = packages: defaultHandler: {
    enable = mkOption {
      type = bool;
      default = cfg.enableAll;
    };
    packages = mkOption {
      type = listOf package;
      default = packages;
    };
    default = mkOption {
      type = str;
      default = defaultHandler;
    };
  };
in
{
  options.modules.media = {
    enableAll = mkEnableOption "";
    setMime = mkOption {
      type = bool;
      default = true;
    };
    audio = mkMedia [
      pkgs.feishin
      pkgs.amberol
    ] "io.bassi.Amberol.desktop";
    video = mkMedia [
      pkgs.vlc
    ] "vlc.desktop";
    image = mkMedia [
      pkgs.loupe
    ] "org.gnome.Loupe.desktop";
    ebook = mkMedia [
      pkgs.calibre
      pkgs.foliate
    ] "com.github.johnfactotum.Foliate.desktop";
  };

  config =
    let
      anyEnabled = any (e: e) [
        cfg.audio.enable
        cfg.video.enable
        cfg.ebook.enable
      ];
    in
    mkIf anyEnabled {
      environment.systemPackages = flatten (
        map (opt: opt.packages) (
          filter (opt: opt.enable) [
            cfg.audio
            cfg.video
            cfg.ebook
          ]
        )
      );

      xdg.mime = mkIf cfg.setMime {
        enable = true;
        defaultApplications = {
          "video/*" = cfg.ebook.default;
          "image/*" = cfg.image.default;
          "audio/*" = cfg.audio.default;
          "audio/mpeg" = cfg.audio.default;
          # Ebooks sadly don't have a singular major type.
          "application/epub+zip" = cfg.ebook.default;
        };
      };
    };
}
