local addonName, addon = ...
local UI = addon.UI

function UI:RefreshCategoryManager()
    local frame = self.CategoryManagerFrame
    if not frame or not frame.Content then return end

    self:ClearFrame(frame.Content)
    local list = addon.DB:GetCustomCategories()
    local y = -2

    if #list == 0 then
        local empty = frame.Content:CreateFontString(nil, "OVERLAY")
        empty:SetFontObject(GameFontNormal)
        empty:SetPoint("TOPLEFT", frame.Content, "TOPLEFT", 4, y)
        empty:SetText(self:T("NO_CUSTOM_CATEGORIES", "NO CUSTOM CATEGORIES"))
        empty:SetTextColor(unpack(self.COLORS.muted))
        y = y - 30
    else
        for _, category in ipairs(list) do
            local row = CreateFrame("Frame", nil, frame.Content, "BackdropTemplate")
            row:SetSize(285, 34)
            row:SetPoint("TOPLEFT", frame.Content, "TOPLEFT", 0, y)
            row:SetBackdrop({
                bgFile = "Interface\\Buttons\\WHITE8X8",
                edgeFile = "Interface\\Buttons\\WHITE8X8",
                edgeSize = 1,
            })
            row:SetBackdropColor(0.04, 0.04, 0.055, 0.8)
            row:SetBackdropBorderColor(unpack(self.COLORS.border))

            local text = row:CreateFontString(nil, "OVERLAY")
            text:SetFontObject(GameFontNormal)
            text:SetPoint("LEFT", row, "LEFT", 8, 0)
            text:SetPoint("RIGHT", row, "RIGHT", -42, 0)
            text:SetJustifyH("LEFT")
            text:SetWordWrap(false)
            text:SetText(category.name)

            local deleteButton = CreateFrame("Button", nil, row, "UIPanelButtonTemplate")
            deleteButton:SetSize(28, 24)
            deleteButton:SetPoint("RIGHT", row, "RIGHT", -4, 0)
            deleteButton:SetText("X")
            deleteButton:SetScript("OnClick", function()
                addon.DB:DeleteCustomCategory(category.id)

                if UI.NewTaskCategory == category.id then
                    UI.NewTaskCategory = addon.DB.CATEGORIES.OTHER
                    if UI.CategoryDropDown then
                        UIDropDownMenu_SetText(UI.CategoryDropDown, UI:T("OTHER", "OTHER"))
                    end
                    if UI.ResetNewTaskContext then UI:ResetNewTaskContext() end
                end

                if UI.CategoryFilter == category.id then
                    if UI.ResetAllFilters then UI:ResetAllFilters() else UI.CategoryFilter = "ALL" end
                end

                UI:RefreshCategoryManager()
                if UI.RefreshDynamicSelectors then UI:RefreshDynamicSelectors() end
                UI:Refresh()
            end)

            y = y - 39
        end
    end

    frame.Content:SetHeight(math.max(math.abs(y) + 8, 60))
end

function UI:ShowCategoryManager()
    if self.CategoryManagerFrame then
        self.CategoryManagerFrame:Show()
        self:RefreshCategoryManager()
        self.CategoryManagerInput:SetFocus()
        return
    end

    local frame = CreateFrame(
        "Frame", "WhatsNextCategoryManager", self.MainFrame, "BackdropTemplate"
    )
    self.CategoryManagerFrame = frame
    frame:SetSize(340, 330)
    frame:SetPoint("CENTER", self.MainFrame, "CENTER", 0, 10)
    frame:SetFrameStrata("TOOLTIP")
    frame:EnableMouse(true)
    frame:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8X8",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        edgeSize = 12,
    })
    frame:SetBackdropColor(unpack(self.COLORS.panel))
    frame:SetBackdropBorderColor(unpack(self.COLORS.border))

    local title = frame:CreateFontString(nil, "OVERLAY")
    title:SetFontObject(GameFontNormalLarge)
    title:SetPoint("TOPLEFT", frame, "TOPLEFT", 12, -12)
    title:SetText(self:T("CUSTOM_CATEGORIES", "CUSTOM CATEGORIES"))
    title:SetTextColor(unpack(self.COLORS.gold))

    local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
    close:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -2, -2)
    close:SetScript("OnClick", function() frame:Hide() end)

    local input = CreateFrame("EditBox", nil, frame, "InputBoxTemplate")
    self.CategoryManagerInput = input
    input:SetPoint("TOPLEFT", frame, "TOPLEFT", 14, -48)
    input:SetSize(220, 28)
    input:SetAutoFocus(false)
    input:SetMaxLetters(30)

    local add = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    add:SetSize(78, 26)
    add:SetPoint("LEFT", input, "RIGHT", 10, 0)
    add:SetText(self:T("CREATE", "ADD"))

    local status = frame:CreateFontString(nil, "OVERLAY")
    status:SetFontObject(GameFontNormalSmall)
    status:SetPoint("TOPLEFT", input, "BOTTOMLEFT", 2, -4)
    status:SetPoint("RIGHT", frame, "RIGHT", -12, 0)
    status:SetJustifyH("LEFT")
    status:SetTextColor(unpack(self.COLORS.muted))

    local function AddCategory()
        local category, errorCode = addon.DB:AddCustomCategory(input:GetText())
        if category then
            input:SetText("")
            status:SetText(UI:T("CATEGORY_ADDED", "CATEGORY ADDED"))
            UI.NewTaskCategory = category.id
            if UI.CategoryDropDown then
                UIDropDownMenu_SetText(UI.CategoryDropDown, category.name)
            end
            if UI.ResetNewTaskContext then UI:ResetNewTaskContext() end
            UI:RefreshCategoryManager()
            if UI.RefreshDynamicSelectors then UI:RefreshDynamicSelectors() end
            UI:Refresh()
        elseif errorCode == "EXISTS" then
            status:SetText(UI:T("CATEGORY_EXISTS", "CATEGORY ALREADY EXISTS"))
        else
            status:SetText(UI:T("ENTER_CATEGORY_NAME", "ENTER CATEGORY NAME"))
        end
    end

    add:SetScript("OnClick", AddCategory)
    input:SetScript("OnEnterPressed", AddCategory)

    local scroll = CreateFrame(
        "ScrollFrame", "WhatsNextCategoryManagerScroll", frame,
        "UIPanelScrollFrameTemplate"
    )
    scroll:SetPoint("TOPLEFT", frame, "TOPLEFT", 14, -100)
    scroll:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -30, 14)

    local content = CreateFrame("Frame", nil, scroll)
    frame.Content = content
    content:SetWidth(285)
    content:SetHeight(60)
    scroll:SetScrollChild(content)

    self:RefreshCategoryManager()
    frame:Show()
    input:SetFocus()
end
