local telescope = require('telescope.builtin')
local wk = require('which-key')
local harpoon = require("harpoon")
local telescope_conf = require("telescope.config").values
harpoon:setup()

vim.keymap.set('n', '<leader>f', telescope.find_files, { desc = "File picker" })
vim.keymap.set('n', '<leader>g', telescope.live_grep, { desc = "Grep recursively" })
vim.keymap.set('n', '<leader>b', telescope.buffers, { desc = "Buffer picker" })
vim.keymap.set('n', '<leader>?', telescope.help_tags, { desc = "Help tags picker" })
vim.keymap.set('n', '<leader>s', telescope.treesitter, { desc = "Treesitter symbol picker" })
vim.keymap.set('n', '<leader>j', telescope.jumplist, { desc = "Jumplist" })
vim.keymap.set('n', '<leader>u', ":TodoTelescope<Enter>", { desc = "Grep for TODOs" })
vim.keymap.set('n', 'U', ":redo<Enter>", {})
vim.keymap.set('n', '<leader>p', ":b#<Enter>", { desc = "Go to last buffer" })



local function toggle_telescope(harpoon_files)
	local displayer = require("telescope.pickers.entry_display").create({
		separator = " | ",
		items = {
			--{ width = 0.1 },
			{ width = 0.9 },
		}
	})

	local harpoons = {}
	for _, item in ipairs(harpoon_files.items) do
		table.insert(harpoons, {
			filepath = item.value,
			col = item.context.col,
			row = item.context.row,
		})
	end

	require("telescope.pickers").new({}, {
		prompt_title = "Harpoon",
		finder = require("telescope.finders").new_table({
			results = harpoons,
			entry_maker = function(entry)
				--vim.print("mapping entry")
				--vim.print(entry)
				local filepath_with_row = string.format("%s:%d", entry.filepath, entry.row)
				return {
					-- Value to display. Required. type=any
					--value = { "foo", entry.filepath, },
					value = entry,

					-- Whether to display the entry. Optional. type=bool
					valid = true,

					-- Optional. type=string|function
					--display = entry.filepath,
					display = function(entry)
						return displayer({
							-- NOTE: the number of elements must match the
							-- configuration passed to `displayer` above
							--{ "foobar" },
							{ filepath_with_row }
						})
					end,

					-- Used for filtering. Optional. type=string
					ordinal = filepath_with_row,

					-- File to open when pressing enter. Optional. type=string
					filename = entry.filepath,

					-- Buffer to open when pressing enter. Optional. type=number
					-- bufnr = 0,

					-- Line number of file/buffer to open. Optional. type=number
					lnum = entry.row,

					-- Line number of file/buffer to open. Optional. type=number
					col = entry.row,
				}
			end
		}),
		previewer = telescope_conf.grep_previewer({}),
		sorter = telescope_conf.generic_sorter({}),
	}):find()
end
vim.keymap.set("n", "<leader>h", function() toggle_telescope(harpoon:list()) end,
	{ desc = "Open harpoon window" })
vim.keymap.set("n", "<leader>H", function() harpoon:list():add() end,
	{ desc = "Launch harpoon" })
-- Toggle previous & next buffers stored within Harpoon list
--vim.keymap.set("n", "<C-S-P>", function() harpoon:list():prev() end)
--vim.keymap.set("n", "<C-S-N>", function() harpoon:list():next() end)


-- Use LspAttach autocommand to only map the following keys
-- after the language server attaches to the current buffer
vim.api.nvim_create_autocmd('LspAttach', {
	group = vim.api.nvim_create_augroup('UserLspConfig', {}),
	callback = function(ev)
		-- Enable completion triggered by <c-x><c-o>
		vim.bo[ev.buf].omnifunc = 'v:lua.vim.lsp.omnifunc'

		-- Buffer local mappings.
		-- See `:help vim.lsp.*` for documentation on any of the below functions
		vim.keymap.set('n', '<leader>ld', telescope.lsp_definitions, { desc = "Show definitons", buffer = ev.buf })
		vim.keymap.set('n', '<leader>lr', telescope.lsp_references, { desc = "Show references", buffer = ev.buf })
		vim.keymap.set('n', '<leader>li', telescope.lsp_implementations,
			{ desc = "Show implementations", buffer = ev.buf })
		vim.keymap.set('n', '<leader>lt', telescope.lsp_type_definitions,
			{ desc = "Show type definitions", buffer = ev.buf })
		vim.keymap.set('n', '<leader>le', telescope.diagnostics, { desc = "Show diagnostics", buffer = ev.buf })
		vim.keymap.set('n', '<leader>ls', telescope.lsp_workspace_symbols,
			{ desc = "Show workspace symbols", buffer = ev.buf })
		vim.keymap.set('n', 'K', vim.lsp.buf.hover, { buffer = ev.buf })
		vim.keymap.set('n', '<C-k>', vim.lsp.buf.signature_help, { buffer = ev.buf })
		vim.keymap.set('n', '<leader>wa', vim.lsp.buf.add_workspace_folder,
			{ desc = "Add workspace folder", buffer = ev.buf })
		vim.keymap.set('n', '<leader>wr', vim.lsp.buf.remove_workspace_folder,
			{ desc = "Remove workspace folder", buffer = ev.buf })
		vim.keymap.set('n', '<leader>wl', function()
			print(vim.inspect(vim.lsp.buf.list_workspace_folders()))
		end, { desc = "List workspace folders", buffer = ev.buf })
		vim.keymap.set('n', '<leader>r', vim.lsp.buf.rename, { desc = "Rename symbol", buffer = ev.buf })
		vim.keymap.set('n', "<leader>a", vim.lsp.buf.code_action, { desc = "Code Action", buffer = ev.buf })

		wk.add({
			{ "<leader>l", desc = "Language server stuff" },
			{ "<leader>w", desc = "Workspace stuff" },
		})
	end,
})

--local rust_tools = require("rust-tools")

--rust_tools.setup({
--  server = {
--    on_attach = function(_, bufnr)
--      -- Hover actions
--      vim.keymap.set("n", "<C-space>", rust_tools.hover_actions.hover_actions, { buffer = bufnr })
--      -- Code action groups
--      vim.keymap.set("n", "<leader>a", rust_tools.code_action_group.code_action_group, { desc = "Code actions", buffer = bufnr })
--    end,
--    settings = {
--      ["rust-analyzer"] = {},
--    }
--  },
--})
