local builtin = require('telescope.builtin')
local codeactions = require("actions-preview")
local telescope = require('telescope')

-- Clear trailing whitespace
vim.keymap.set("n", "<C-w>", "<cmd>let _s=@/<Bar>:%s/\\s\\+$//e<Bar>:let @/=_s<Bar><CR>")

-- Use tab and shift+tab to cycle buffers
vim.keymap.set("n", "<tab>", "<cmd>bn<cr>")
vim.keymap.set("n", "<S-tab>", "<cmd>bp<cr>")

-- Turn spellchecker on and off
vim.keymap.set("n", "<leader>se", "<cmd>setlocal spell spelllang=en_us<cr>")
vim.keymap.set("n", "<leader>sq", "<cmd>setlocal nospell<cr>")

vim.keymap.set("n", "<F3>", "<cmd>set nonumber!<CR>")
vim.keymap.set("n", "<leader>e", "<cmd>Oil<CR>")

vim.keymap.set("n", ']d', "<cmd>lua vim.diagnostic.goto_next()<CR>")
vim.keymap.set("n", '[d', "<cmd>lua vim.diagnostic.goto_prev()<CR>")

-- Outline!!
vim.keymap.set("n", "<leader>o", "<cmd>Outline<CR>")

-- Close all buffers
vim.keymap.set("n", '<C-S-x>', "<cmd>bufdo bd<CR>")

vim.keymap.set("n", "<M-r>", "<cmd>lua vim.lsp.buf.rename()()<CR>")
vim.keymap.set("n", "<leader>wl", "<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>")
vim.keymap.set("n", "<leader>wa", "<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>")
vim.keymap.set("n", "<leader>wr", "<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>")

-- Snippets can be useful.
vim.keymap.set('n', '<leader>ss', telescope.extensions.luasnip.luasnip, {})

-- Fuzzy * files, symbols, buffers, help, etc.
vim.keymap.set("n", "<leader>a", codeactions.code_actions)
vim.keymap.set('n', '<leader>F', builtin.find_files) -- f[ind]a[ll]
vim.keymap.set('n', '<leader>b', builtin.buffers)
vim.keymap.set('n', '<leader>d', builtin.diagnostics)
vim.keymap.set('n', '<leader>f', builtin.git_files)
vim.keymap.set('n', '<leader>h', builtin.help_tags)
vim.keymap.set('n', '<leader>ws', builtin.lsp_dynamic_workspace_symbols)

-- Grep (the only one).
vim.keymap.set('n', '<leader>rg', builtin.live_grep)

-- LSP navigation.
vim.keymap.set('n', 'gd', builtin.lsp_definitions)
vim.keymap.set('n', 'gr', builtin.lsp_references)
vim.keymap.set('n', 'gi', builtin.lsp_implementations)
vim.keymap.set('n', '<leader>ci', builtin.lsp_incoming_calls)
vim.keymap.set('n', '<leader>co', builtin.lsp_outgoing_calls)

vim.keymap.set('n', '<leader>x', function()
  -- Check if diagnostics are currently enabled for the current buffer
  if vim.diagnostic.is_enabled() then
    vim.diagnostic.enable(false)
  else
    vim.diagnostic.enable()
  end
end, { noremap = true, silent = true, desc = "Toggle diagnostics" })
