local lsp_lines = require("lsp_lines")
lsp_lines.setup()
-- Disable virtual_text since it's redundant due to lsp_lines.
vim.diagnostic.config({
  virtual_text = false,
})

-- The nvim-cmp almost supports LSP's capabilities so You should advertise it to LSP servers..
local capabilities = require("cmp_nvim_lsp").default_capabilities()

-- Tell the server the capability of foldingRange,
-- Neovim hasn't added foldingRange to default capabilities, users must add it manually
capabilities.textDocument.foldingRange = {
  dynamicRegistration = false,
  lineFoldingOnly = true,
}
-- NOTE https://github.com/neovim/neovim/pull/22405
capabilities.didChangeWatchedFiles = {
  dynamicRegistration = true,
}

local lspconfig = require("lspconfig")
local on_attach_def = function(client, bufnr)
  require("which-key").add({
    { "<leader>c", buffer = bufnr, group = "code" },
    {
      "<leader>cr",
      function()
        return ":IncRename " .. vim.fn.expand("<cword>")
      end,
      buffer = bufnr,
      desc = "Rename",
      expr = true,
      replace_keycodes = false,
    },
    {
      "<leader>ti",
      function()
        vim.lsp.inlay_hint.enable(not vim.lsp.inlay_hint.is_enabled())
      end,
      buffer = bufnr,
      desc = "LSP inlay hints",
    },
    {
      "<leader>tl",
      function()
        lsp_lines.toggle()
        if vim.diagnostic.is_disabled() then
          vim.diagnostic.enable()
        else
          vim.diagnostic.disable()
        end
      end,
      buffer = bufnr,
      desc = "LSP lines",
    },
    { "K", vim.lsp.buf.hover, buffer = bufnr, desc = "Hover" },
    { "[d", vim.diagnostic.goto_prev, buffer = bufnr, desc = "Previous diagnostic" },
    { "]d", vim.diagnostic.goto_next, buffer = bufnr, desc = "Next diagnostic" },
    { "gD", vim.lsp.buf.declaration, buffer = bufnr, desc = "Goto declaration" },
    { "gI", "<cmd>Telescope lsp_implementations<cr>", buffer = bufnr, desc = "Goto implementation" },
    { "gK", vim.lsp.buf.signature_help, buffer = bufnr, desc = "Signature help" },
    {
      "gd",
      function()
        require("telescope.builtin").lsp_definitions({ reuse_win = true })
      end,
      buffer = bufnr,
      desc = "Goto definition",
    },
    { "gr", "<cmd>Telescope lsp_references<cr>", buffer = bufnr, desc = "Goto references" },
    {
      "gt",

      function()
        require("telescope.builtin").lsp_type_definitions({ reuse_win = true })
      end,
      buffer = bufnr,
      desc = "Goto type definition",
    },
    {
      "<leader>cc",
      require("actions-preview").code_actions,
      buffer = bufnr,
      desc = "Code action",
      mode = { "n", "v" },
    },
    {
      "<leader>cf",
      function()
        vim.lsp.buf.format({ async = true })
      end,
      buffer = bufnr,
      desc = "Format (lsp)",
      mode = { "n", "v" },
    },
  })
  if client.server_capabilities.inlayHintProvider then
    local slow_lsp_servers = {
      "rust_analyzer",
    }
    local timeout = vim.tbl_contains(slow_lsp_servers, client.name, {}) and 500 or 0
    vim.defer_fn(function()
      vim.lsp.inlay_hint.enable(true, { bufnr })
    end, timeout)
  end
end

local lspconfig_default_options = {
  on_attach = on_attach_def,
  capabilities = capabilities,
  flags = {
    debounce_text_changes = 100,
  },
}

---function to add default options to lspconfig
---@param lsp string
---@param options table
---@return nil
local function lspconfig_setup(lsp, options)
  local final_options = vim.tbl_deep_extend("force", lspconfig_default_options, options)
  lspconfig[lsp].setup(final_options)
end

local servers = {
  "bashls",
  "gleam",
  "gopls",
  "pylsp",
  "ruff",
  "templ",
  "typst_lsp",
}
for _, lsp in ipairs(servers) do
  lspconfig_setup(lsp, {})
end

lspconfig_setup("elixirls", {
  cmd = { "elixir-ls" },
})

lspconfig_setup("nil_ls", {
  settings = {
    flake = {
      autoArchive = true,
      autoEvalInputs = true,
      nixpkgsInputName = "nixpkgs",
    },
  },
})

lspconfig_setup("nixd", {
  settings = {
    nixd = {
      nixpkgs = {
        expr = "import <nixpkgs> { }",
      },
      options = {
        nixos = {
          expr = '(builtins.getFlake ("git+file://" + toString ./.)).nixosConfigurations.nixos-desktop.options',
        },
        ["flake-parts"] = {
          expr = '(builtins.getFlake ("git+file://" + toString ./.)).debug.options',
        },
        ["flake-parts2"] = {
          expr = '(builtins.getFlake ("git+file://" + toString ./.)).currentSystem.options',
        },
      },
    },
  },
})

-- Add templ filetype
vim.filetype.add({ extension = { templ = "templ" } })

lspconfig_setup("htmx", {
  filetypes = { "html", "templ" },
})

lspconfig_setup("tailwindcss", {
  filetypes = { "templ", "astro", "javascript", "typescript", "react" },
  init_options = { userLanguages = { templ = "html" } },
})

lspconfig_setup("rust_analyzer", {
  settings = {
    ["rust-analyzer"] = {
      checkOnSave = {
        command = "clippy",
      },
    },
  },
})

lspconfig_setup("lua_ls", {
  settings = {
    Lua = {
      runtime = {
        -- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
        version = "LuaJIT",
        path = vim.split(package.path, ";"),
      },
      diagnostics = {
        -- Get the language server to recognize the `vim` global
        globals = { "vim" },
      },
      workspace = {
        -- Make the server aware of Neovim runtime files
        library = vim.api.nvim_get_runtime_file("", true),
        checkThirdParty = false,
      },
      -- Do not send telemetry data containing a randomized but unique identifier
      telemetry = {
        enable = false,
      },
      format = {
        enable = false,
      },
      hint = {
        enable = true,
      },
    },
  },
})
