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

let
  inherit (lib)
    literalExpression
    mkIf
    mkMerge
    mkEnableOption
    mkOption
    types
    ;

  cfg = config.programs.wezterm;

  tomlFormat = pkgs.formats.toml { };

  shellIntegrationStr = ''
    source "${cfg.package}/etc/profile.d/wezterm.sh"
  '';
in
{
  meta.maintainers = [
    lib.hm.maintainers.blmhemu
    lib.maintainers.khaneliman
    lib.hm.maintainers.philip-730
  ];

  options.programs.wezterm = {
    enable = mkEnableOption "wezterm";

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

    settings = mkOption {
      type = types.attrsOf types.anything;
      default = { };
      example = literalExpression ''
        {
          color_scheme = "Catppuccin Mocha";
          font_size = 13;
          hide_tab_bar_if_only_one_tab = true;
          window_padding = {
            left = 0;
            right = 0;
            top = 0;
            bottom = 0;
          };
          font = lib.generators.mkLuaInline '''wezterm.font("JetBrains Mono")''';
        }
      '';
      description = ''
        Configuration written to
        {file}`$XDG_CONFIG_HOME/wezterm/wezterm.lua` using
        `lib.generators.toLua`. Values created with
        `lib.generators.mkLuaInline` are rendered as raw Lua
        expressions, which allows embedding wezterm API calls such as
        `wezterm.font`. See
        <https://wezfurlong.org/wezterm/config/files.html> for
        available options.

        When this option is set, {option}`extraConfig` is still
        supported. Any table returned from the extra Lua code is merged
        on top of these settings, so {option}`extraConfig` takes
        precedence on conflicts.
      '';
    };

    extraConfig = mkOption {
      type = types.lines;
      default = "";
      example = literalExpression ''
        -- Your lua code / config here
        local mylib = require 'mylib';
        return {
          usemylib = mylib.do_fun();
          font = wezterm.font("JetBrains Mono"),
          font_size = 16.0,
          color_scheme = "Tomorrow Night",
          hide_tab_bar_if_only_one_tab = true,
          default_prog = { "zsh", "--login", "-c", "tmux attach -t dev || tmux new -s dev" },
          keys = {
            {key="n", mods="SHIFT|CTRL", action="ToggleFullScreen"},
          }
        }
      '';
      description = ''
        Extra configuration written to
        {file}`$XDG_CONFIG_HOME/wezterm/wezterm.lua`. See
        <https://wezfurlong.org/wezterm/config/files.html>
        how to configure.

        When used together with {option}`settings`, any table returned
        from this Lua code is merged into the generated configuration,
        taking precedence over {option}`settings` on conflicts. Note
        that this merge is shallow: a key returned here replaces the
        entire corresponding value from {option}`settings`, so nested
        tables and arrays are not combined. A {command}`return`
        statement is optional — code that directly modifies the
        {command}`config` variable also works.
      '';
    };

    colorSchemes = mkOption {
      type = types.attrsOf (tomlFormat.type);
      default = { };
      example = literalExpression ''
        myCoolTheme = {
          ansi = [
            "#222222" "#D14949" "#48874F" "#AFA75A"
            "#599797" "#8F6089" "#5C9FA8" "#8C8C8C"
          ];
          brights = [
            "#444444" "#FF6D6D" "#89FF95" "#FFF484"
            "#97DDFF" "#FDAAF2" "#85F5DA" "#E9E9E9"
          ];
          background = "#1B1B1B";
          cursor_bg = "#BEAF8A";
          cursor_border = "#BEAF8A";
          cursor_fg = "#1B1B1B";
          foreground = "#BEAF8A";
          selection_bg = "#444444";
          selection_fg = "#E9E9E9";
        };
      '';
      description = ''
        Attribute set of additional color schemes to be written to
        {file}`$XDG_CONFIG_HOME/wezterm/colors`, where each key is
        taken as the name of the corresponding color scheme. See
        <https://wezfurlong.org/wezterm/config/appearance.html#defining-a-color-scheme-in-a-separate-file>
        for more details of the TOML color scheme format.
      '';
    };

    enableBashIntegration = lib.hm.shell.mkBashIntegrationOption { inherit config; };

    enableZshIntegration = lib.hm.shell.mkZshIntegrationOption { inherit config; };
  };

  config = mkIf cfg.enable {
    home.packages = [ cfg.package ];

    xdg.configFile =
      let
        hasSettings = cfg.settings != { };
      in
      mkMerge [
        (mkIf (hasSettings || cfg.extraConfig != "") {
          "wezterm/wezterm.lua".text =
            if hasSettings then
              ''
                -- Generated by Home Manager.
                -- See https://wezfurlong.org/wezterm/

                local wezterm = require 'wezterm'
                local config = wezterm.config_builder and wezterm.config_builder() or {}

                local hm_config = ${lib.generators.toLua { } cfg.settings}
                for k, v in pairs(hm_config) do
                  config[k] = v
                end

                ${lib.optionalString (cfg.extraConfig != "") ''
                  local _hm_extra = (function()
                    ${cfg.extraConfig}
                  end)()
                  if type(_hm_extra) == "table" then
                    for k, v in pairs(_hm_extra) do
                      config[k] = v
                    end
                  end
                ''}
                return config
              ''
            else
              ''
                -- Generated by Home Manager.
                -- See https://wezfurlong.org/wezterm/

                local wezterm = require 'wezterm'

                ${cfg.extraConfig}
              '';
        })
        (lib.mapAttrs' (
          name: value:
          lib.nameValuePair "wezterm/colors/${name}.toml" {
            source = tomlFormat.generate "${name}.toml" { colors = value; };
          }
        ) cfg.colorSchemes)
      ];

    programs.bash.initExtra = mkIf cfg.enableBashIntegration shellIntegrationStr;
    programs.zsh.initContent = mkIf cfg.enableZshIntegration shellIntegrationStr;
  };
}
