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

let
  cfg = config.snowhawk.neovim;

  nightlyNeovim = inputs.neovim-overlay.packages.${pkgs.system}.default;
in
{
  options.snowhawk.neovim = {
    enable = lib.mkEnableOption "neovim home-manager module";

    nightly = lib.mkEnableOption "nightly build of neovim";

    package = lib.mkOption {
      type = with lib.types; package;
      default = if cfg.nightly then nightlyNeovim else pkgs.neovim-unwrapped;
    };
  };

  config =
    let
      nvim-treesitter = pkgs.vimPlugins.nvim-treesitter;
      treesitterWithGrammars = nvim-treesitter.withAllGrammars;

      treesitter-parsers = pkgs.symlinkJoin {
        name = "treesitter-parsers";
        paths = treesitterWithGrammars.dependencies;
      };
    in
    lib.mkIf cfg.enable {
      snowhawk.repo-clone.enable = true;
      repo-clone.repos = {
        "${config.home.homeDirectory}/.config/nvim".url = lib.zgitRepo "nvim";
      };

      # Set nvim as manpager and default editor
      home.sessionVariables = {
        EDITOR = "nvim";
        MANPAGER = "nvim +Man!";
      };

      xdg.configFile."nvim/lua/parsers.lua".text = /* lua */ ''
        vim.opt.runtimepath:append ("${treesitter-parsers}")
      '';

      programs.neovim = {
        enable = true;
        coc.enable = false;
        package = cfg.package;
        withNodeJs = true;
        withPython3 = true;
        withRuby = true;

        plugins = [
          treesitterWithGrammars
        ];

        extraPackages = with pkgs; [
          marksman
          nil
          nixpkgs-fmt
          rustup
          lua-language-server
          fzf
          stylua
          taplo
          gnumake
          zig
          gcc
          clang-tools
          coreutils
        ];
      };
    };
}