local actions = require('telescope.actions')
local action_state = require('telescope.actions.state')

-- Custom function for search and replace using Telescope
-- test
function _G.search_and_replace()
  local current_file = vim.fn.expand('%:p')
  local query = vim.fn.input('Enter search pattern: ')

  -- Create the Telescope prompt with custom mappings
  require('telescope.builtin').find_files({
    prompt_title = 'Search and Replace',
    cwd = vim.loop.cwd(),
    hidden = true,
    attach_mappings = function(prompt_bufnr, map)
      actions.select_default:replace(function()
        local selection = action_state.get_selected_entry()
        
        -- Get the replace pattern from user
        local replace_query = vim.fn.input('Replace with: ', '')
        
        if not replace_query == '' then
          local args = { query, replace_query }
          
          -- Open a terminal buffer to run the search and replace command
          require('telescope.builtin').terminal_job({
            cmd = {
              'sh', '-c',
              string.format(
                "grep -rl '%s' . | xargs sed -i 's/%s/%s/g'",
                table.concat(args, "'"),
                query,
                replace_query
              )
            },
            cwd = vim.fn.expand('%:p:h'),
          })
        end

        return true
      end)
      
      return true
    end
  })
end

return {
	-- fuzzy finder
	"nvim-telescope/telescope.nvim",
	dependencies = {
		"nvim-lua/plenary.nvim",
	},
	config = function()
		local builtin = require("telescope.builtin")
		local actions = require("telescope.actions")
		local opts = { silent = true }

		require("telescope").setup({
			defaults = {
				mappings = {
					i = {
						["<C-j>"] = actions.move_selection_next,
						["<C-k>"] = actions.move_selection_previous,
						["<C-q>"] = actions.send_selected_to_qflist + actions.open_qflist, -- TODO investigate
					},
				},
			},
		})

		opts.desc = "telescope find files"
		vim.keymap.set("n", "<leader>ff", builtin.find_files, opts)

		opts.desc = "telescope live grep"
		vim.keymap.set("n", "<leader>fg", builtin.live_grep, opts)

		opts.desc = "telescope buffers"
		vim.keymap.set("n", "<leader>fb", builtin.buffers, opts)

		opts.desc = "telescope nvim functions"
		vim.keymap.set("n", "<leader>fh", builtin.help_tags, opts)


		-- Search and replace
		
	end,
}