local vim = vim
local fzflua = require("fzf-lua")
local Job = require'plenary.job'

function t3_find_file()
  -- local file_name = vim.fn.input("Find File: ", "", "file")
  fzflua.files()
end

function t3_recent_files()
  fzflua.oldfiles()
end

function t3_org_files()
  fzflua.files({ cwd = '~/org/'})
end

function t3_project_files()
  fzflua.files({ cwd = '~/Projects/'})
end

function t3_dot_files()
  fzflua.files({ cwd = '~/.dotfiles/'})
end

function t3_config_files()
  fzflua.files({ cwd = '~/.dotfiles/'})
end

function t3_snip_capture(name)
  if type(name) ~= "string" or name == "" then
    print("Error: Invalid snippet name")
    return
  end
  -- local timestamp = os.date("%Y%m%d%H%M%S")
  local snippet_path = "~/.config/nvim/snippets/"
  local filename = snippet_path .. name:gsub("%s+", "_") .. ".lua"
  local file = io.open(vim.fn.expand(filename), "w")
    if file == nil then
    print("Error: Could not open file for editing.")
    return
  end
  local previous_buffer = vim.api.nvim_get_current_buf()
  file:write("local ls = require('luasnip')\n\nls.add_snippets(\"{}\", {\n\tls.parser.parse_snippet(\n\t\t'{}',\n\t\t'{}'),\n})")
  file:close()
  vim.cmd("e " .. filename)
  vim.bo.filetype = 'lua'
  -- vim.cmd("Neorg inject-metadata")
  -- Set an autocmd to return to the previous buffer when the note buffer is closed
  vim.api.nvim_create_autocmd("BufLeave", {
      buffer = 0,  -- Current buffer (the note buffer)
      callback = function()
          load_snippets_from_directory(snippet_path)
          vim.cmd("buffer " .. previous_buffer)
      end,
  })
  print("Captured snippet: " .. filename)
end

function t3_org_capture(name)
  if type(name) ~= "string" or name == "" then
    print("Error: Invalid note name")
    return
  end
  local timestamp = os.date("%Y%m%d%H%M%S")
  local org_path = "~/org/.org-roam/"
  local filename = org_path .. timestamp .. "-" .. name:gsub("%s+", "_") .. ".norg"
  local file = io.open(vim.fn.expand(filename), "w")
  if file == nil then
    print("Error: Could not open file for editing.")
    return
  end
  local previous_buffer = vim.api.nvim_get_current_buf()
  file:write("* " .. name .. "\n\n")
  file:close()
  vim.cmd("e " .. filename)
  vim.bo.filetype = 'norg'
  vim.cmd("Neorg inject-metadata")
  -- Set an autocmd to return to the previous buffer when the note buffer is closed
  vim.api.nvim_create_autocmd("BufLeave", {
      buffer = 0,  -- Current buffer (the note buffer)
      callback = function()
          vim.cmd("buffer " .. previous_buffer)
      end,
  })
  print("Captured note: " .. filename)
end

vim.api.nvim_create_user_command(
  'NeorgCapture',
    function()
      -- local title = vim.fn.input("Title: ")
      local current_workspace = vim.g.neorg_workspace_name
      if not current_workspace then
        vim.cmd("Neorg workspace default")
      end
      vim.ui.input({ prompt = "Enter note name: "}, function(note_name)
          if not note_name or note_name == "" then
            print("Error: Note name required!")
            return
          end
        t3_org_capture(note_name)
        end
      )
    end,
  { nargs = 0, desc = "Capture a Neorg note" }
)

vim.api.nvim_create_user_command(
  'CaptureSnip',
    function()
      -- local title = vim.fn.input("Title: ")
      -- local current_workspace = vim.g.neorg_workspace_name
      -- if not current_workspace then
      --   vim.cmd("Neorg workspace default")
      -- end
      vim.ui.input({ prompt = "Enter snippet name: "}, function(snip_name)
          if not snip_name or snip_name == "" then
            print("Error: Snippet name required!")
            return
          end
        t3_snip_capture(snip_name)
        end
      )
    end,
  { nargs = 0, desc = "Capture a Neorg note" }
)
function t3_buffers()
  fzflua.buffers()
end

function t3_tabs()
  fzflua.tabs()
end

function t3_live_grep(state)
  state = state or 0
  if state == 0 then
    fzflua.live_grep()
  else
    fzflua.live_grep_resume()
  end
end

function t3_grep(state)
  state = state or 0
  if state == 0 then
    fzflua.grep_project()
  else
    fzflua.grep()
  end
end
function t3_make_ctags()
  Job:new({
    command = 'ctags',
    args = { '-R .' },
  })
end

vim.api.nvim_create_autocmd("FileType", {
  pattern = { "markdown", "norg", "md", "wiki" },  -- Set for markdown file type
  callback = function()
    vim.api.nvim_buf_set_keymap(0, "n", "<C-i>", "o* [ ] ", { noremap = true, silent = true })
    vim.api.nvim_buf_set_keymap(0, "i", "<C-i>", "<Esc>0wi* [ ] ", { noremap = true, silent = true })
  end,
})
