{ config, lib, ... }:

let
  cfg = config.programs.nixvim;
  plugin = cfg.plugins.gitsigns;

  inherit (lib) mkDefault mkIf;
in
{
  config = {
    programs.nixvim = {
      plugins.gitsigns = {
        enable = mkDefault true;
        settings = {
          current_line_blame = mkDefault false;
          current_line_blame_opts = {
            virt_text = mkDefault true;
            virt_text_pos = mkDefault "eol";
          };
          signcolumn = mkDefault true;
          signs = {
            add.text = mkDefault "+";
            change.text = mkDefault "│";
            changedelete.text = mkDefault "~";
            delete.text = mkDefault "-";
            topdelete.text = mkDefault "-";
            untracked.text = mkDefault "?";
          };
          watch_gitdir.follow_files = mkDefault true;
        };
      };
      keymaps = mkIf plugin.enable [
        {
          mode = "n";
          key = "<leader>hs";
          action.__raw = "function() require('gitsigns').stage_hunk() end";
          options = {
            noremap = true;
            silent = true;
            desc = "stage hunk";
          };
        }
        {
          mode = "v";
          key = "<leader>hs";
          action.__raw = ''
            function()
              require('gitsigns').stage_hunk({vim.fn.line('.'), vim.fn.line('v')})
            end
          '';
          options = {
            noremap = true;
            silent = true;
            desc = "stage selected hunks";
          };
        }
        {
          mode = "n";
          key = "<leader>hu";
          action.__raw = "function() require('gitsigns').undo_stage_hunk() end";
          options = {
            noremap = true;
            silent = true;
            desc = "undo stage hunk";
          };
        }
        {
          mode = "n";
          key = "<leader>hS";
          action.__raw = "function() require('gitsigns').stage_buffer() end";
          options = {
            noremap = true;
            silent = true;
            desc = "stage buffer";
          };
        }
        {
          mode = "n";
          key = "<leader>hr";
          action.__raw = "function() require('gitsigns').reset_hunk() end";
          options = {
            noremap = true;
            silent = true;
            desc = "reset hunk";
          };
        }
        {
          mode = "v";
          key = "<leader>hr";
          action.__raw = ''
            function()
              require('gitsigns').reset_hunk({vim.fn.line('.'), vim.fn.line('v')})
            end
          '';
          options = {
            noremap = true;
            silent = true;
            desc = "reset selected hunks";
          };
        }
      ];
    };
  };
}
