local wk = require("which-key")
local builtin = require("telescope.builtin")
local gitsigns = require('gitsigns')

-- local tree = require "nvim-tree.api"

function FormatBuffer(command)
	-- Save the current cursor position
	local cursor_position = vim.fn.getpos(".")

	-- Run the formatter command on the current buffer
	vim.cmd(":%! " .. command)

	-- Restore the cursor position
	vim.fn.setpos(".", cursor_position)
end

function ToggleTree(source)
	require("neo-tree.command").execute({
		toggle = true,
		source = source,
		position = "left",
	})
end

wk.add({
	{
		mode = "n",
		-- telescope
		{
			"<leader>ff",
			function()
				builtin.find_files()
			end,
			desc = "Find file",
		},
		{
			"<leader>fg",
			function()
				builtin.live_grep()
			end,
			desc = "Live grep",
		},
		{
			"<leader>fb",
			function()
				builtin.buffers()
			end,
			desc = "List buffers",
		},
		{
			"<leader>fh",
			function()
				builtin.help_tags()
			end,
			desc = "Help",
		},
		{
			"<leader>fs",
			function()
				builtin.lsp_document_symbols()
			end,
			desc = "Find symbols",
		},
		{
			"zz",
			function()
				builtin.spell_suggest()
			end,
			desc = "Suggest spell",
		},

		-- Centering cursor
		{ "n", "nzzzv", desc = "Center cursor when n (next) during search" },
		{ "N", "Nzzzv", desc = "Center cursor when n (next) during search" },

		-- tab
		{ "<tab>", ":BufferLineCycleNext <CR>", desc = "Next tab" },
		{ "<S-tab>", ":BufferLineCyclePrev<CR>", desc = "Previous tab" },

		-- Comment
		{ "<leader>/", "gcc", desc = "comment toggle", remap = true },

		-- Format
		{
			"<leader>fm",
			function()
				require("conform").format({ lsp_fallback = true })
			end,
			desc = "format files",
		},

		-- nvim-tree
		-- { "<C-n>", function() tree.tree.toggle() end, desc = "Toggle file tree" },
		{
			"<C-n>",
			function()
				ToggleTree("filesystem")
			end,
			desc = "Toggle file tree",
		},

		-- Typst format
		{
			"<leader>ft",
			function()
				FormatBuffer("typstfmt")
			end,
			desc = "Typst formater",
		},

    -- Lsp
    { "K", function() vim.lsp.buf.hover() end, desc = "LSP toggle" },
    { "<leader>ca", function() vim.lsp.buf.code_action() end, desc = "LSP code action" },
    { "<leader>cd", function() vim.diagnostic.setqflist() end, desc = "LSP code diagnostic" },

    -- Gitsigns
    { "<leader>nc", function() gitsigns.nav_hunk('next') end, desc = "Next change" },
    { "<leader>pc", function() gitsigns.nav_hunk('prev') end, desc = "Previous change" },
	},
	{
		mode = "v",
		{ "<S-j>", ":m '>+1<CR>gv=gv", desc = "Move selection down" },
		{ "<S-k>", ":m '<-2<CR>gv=gv", desc = "Move selection up" },

		-- Comment
		{ "<leader>/", "gc", desc = "comment toggle", remap = true },
	},
})
