local M = {}

local hastelescope, telescope= pcall(require, "telescope")

if not hastelescope then
    return M
end

M.git_files = function()
    local opts = require('telescope.themes').get_ivy({})
    opts["show_untracked"] = true
    opts["layout_config"] = {height=0.2}
    if not pcall(require"telescope.builtin".git_files, opts) then
        require"telescope.builtin".find_files(opts)
    end
end

M.project_files = function()
    local opts = require('telescope.themes').get_ivy({})
    opts["layout_config"] = {height=0.2}
    require"telescope.builtin".find_files(opts)
end

M.buffers = function()
    local opts = require('telescope.themes').get_ivy({})
    opts["layout_config"] = {height=0.2}
    require"telescope.builtin".buffers(opts)
end

local actions = require("telescope.actions")
require("telescope").setup{
    defaults = {
        file_ignore_patterns = {
            ".cache/.*",
            "node_modules/.*",
            ".git/.*",
            "Venv/.*",
            "venv/.*",
            "wandb/.*",
            "Resources/.*",
            "build/.*"
        },
        mappings = {
            i = {
                ["jj"] = actions.close,
                ["<C-j>"] = actions.move_selection_next,
                ["<C-k>"] = actions.move_selection_previous,
            },
        },
    },
    extensions = {
        undo = {
            side_by_side = false,
            layout_strategy = "vertical",
            use_delta = true,
            layout_config = {
                preview_height = 0.5,
            },
            mappings = {
                i = {
                    ["<cr>"] = require("telescope-undo.actions").restore,
                    ["<S-y>"] = require("telescope-undo.actions").yank_additions,
                },
            },

        }
    }
}

telescope.load_extension("undo")
telescope.load_extension('fzf')


vim.keymap.set("n", "<leader>u", function() require("telescope").extensions.undo.undo()  end, {noremap = true, silent = true})
vim.keymap.set("n", "<C-p>", function() require('telescope_config').git_files() end, {noremap = true, silent = true})
vim.keymap.set("n", "<C-O>", function() require('telescope_config').project_files() end, { silent = true, noremap = true })
vim.keymap.set("n", "<C-f>", function() require('telescope.builtin').live_grep{ cwd = vim.fn.systemlist("git rev-parse --show-toplevel 2> /dev/null || pwd")[1] } end, { silent = true, noremap = true })

return M
