local _, addonTable = ...
local WipedQoL = addonTable.WipedQoL
local UI = addonTable.UI
local TRANSLATE = addonTable.TRANSLATE or function(msg) return msg end

local EXPANSION_VENDOR_ANCHOR_OPTIONS = {
    { value = "LEFT", label = "Left first" },
    { value = "RIGHT", label = "Right first" },
}

WipedQoL:RegisterTabBuilder("banking", function(addon, parent)
    local frame = CreateFrame("Frame", nil, parent)
    local goldSection = UI.CreateSection(
        frame,
        TRANSLATE("Automatic bank deposit and withdraw"),
        TRANSLATE("Keeps each character at the configured gold amount when using the bank.")
    )
    goldSection:SetPoint("TOPLEFT", frame, "TOPLEFT", 14, -14)
    goldSection:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -14, -14)
    goldSection:SetHeight(120)

    local warboundSection = UI.CreateSection(
        frame,
        TRANSLATE("Automatically deposit Warbound items"),
        TRANSLATE("Automatically deposits Warbound items into the Warband bank. Configure your Warband bank in Blizzard's UI for best results.")
    )
    warboundSection:SetPoint("TOPLEFT", goldSection, "BOTTOMLEFT", 0, -12)
    warboundSection:SetPoint("TOPRIGHT", goldSection, "BOTTOMRIGHT", 0, -12)
    warboundSection:SetHeight(74)

    local settings = addon:GetAutoBankGoldSettings()
    local warboundSettings = addon:GetWarboundBankItemSettings()
    local expansionVendorSettings = addon:GetExpansionVendorSettings()
    local targetLabel
    local targetEditBox
    local excludeLabel
    local excludeDropdown

    local function RefreshTargetState()
        local enabled = settings.enabled == true

        for _, label in ipairs({ targetLabel, excludeLabel }) do
            if label then
                if enabled then
                    label:SetTextColor(0.78, 0.78, 0.78)
                else
                    label:SetTextColor(0.38, 0.38, 0.38)
                end
            end
        end

        if targetEditBox then
            if enabled then
                targetEditBox:Enable()
                targetEditBox:SetTextColor(1, 1, 1, 1)
            else
                targetEditBox:Disable()
                targetEditBox:ClearFocus()
                targetEditBox:SetTextColor(0.45, 0.45, 0.45, 1)
            end
        end

        if excludeDropdown then
            excludeDropdown:SetAlpha(enabled and 1 or 0.45)
            if excludeDropdown._wqolClickOverlay then
                excludeDropdown._wqolClickOverlay:EnableMouse(enabled)
            end
            if not enabled and excludeDropdown.Close then
                excludeDropdown:Close()
            end
        end
    end

    local function GetCharacterOptions()
        local options = {}
        local groups = {}
        local realms = {}

        for _, character in ipairs(addon:GetKnownCharacters()) do
            local realm = character.realm or character.label or ""
            if realm == "" then
                realm = TRANSLATE("Unknown realm")
            end

            if not groups[realm] then
                groups[realm] = {}
                realms[#realms + 1] = realm
            end

            groups[realm][#groups[realm] + 1] = {
                value = character.key,
                label = character.label,
                realm = character.realm,
                classFile = character.classFile,
            }
        end

        table.sort(realms, function(left, right)
            local leftCount = #(groups[left] or {})
            local rightCount = #(groups[right] or {})
            if leftCount ~= rightCount then
                return leftCount > rightCount
            end

            return tostring(left) < tostring(right)
        end)

        for _, realm in ipairs(realms) do
            local characters = groups[realm]
            if #characters > 0 then
                table.sort(characters, function(left, right)
                    return tostring(left.label or "") < tostring(right.label or "")
                end)

                options[#options + 1] = {
                    label = realm,
                    isHeader = true,
                }

                for _, character in ipairs(characters) do
                    options[#options + 1] = character
                end
            end
        end

        return options
    end

    local function GetExcludedCharactersText()
        local options = GetCharacterOptions()
        if #options == 0 then
            return TRANSLATE("No known characters")
        end

        local excluded = 0
        for _, option in ipairs(options) do
            if not option.isHeader and addon:IsAutoBankGoldCharacterExcluded(option.value) then
                excluded = excluded + 1
            end
        end

        if excluded == 0 then
            return TRANSLATE("No character excluded")
        end

        return string.format(TRANSLATE("%d characters excluded"), excluded)
    end

    local enableCheckbox = UI.CreateSectionToggle(goldSection, function()
        return settings.enabled == true
    end, function(value)
        settings.enabled = value and true or false
        RefreshTargetState()
    end)

    targetLabel = UI.CreateLabel(goldSection, TRANSLATE("Target gold per character"), 12)
    targetLabel:SetPoint("TOPLEFT", goldSection.description, "BOTTOMLEFT", 0, -10)
    targetLabel:SetTextColor(0.78, 0.78, 0.78)

    targetEditBox = UI.CreateEditBox(goldSection, function()
        return tostring(settings.targetGold or 0)
    end, function(value)
        addon:SetAutoBankGoldTargetGold(value)
        if targetEditBox then
            targetEditBox:SetText(tostring(settings.targetGold or 0))
        end
    end)
    targetEditBox:SetPoint("TOPLEFT", targetLabel, "BOTTOMLEFT", 0, -6)
    targetEditBox:SetSize(170, 28)
    targetEditBox:SetNumeric(true)

    excludeLabel = UI.CreateLabel(goldSection, TRANSLATE("Excluded characters"), 12)
    excludeLabel:SetPoint("TOPLEFT", targetLabel, "TOPLEFT", 210, 0)
    excludeLabel:SetTextColor(0.78, 0.78, 0.78)

    excludeDropdown = UI.CreateMultiSelectDropdown(goldSection, 220, GetCharacterOptions, function(characterKey)
        return addon:IsAutoBankGoldCharacterExcluded(characterKey)
    end, function(characterKey, excluded)
        addon:SetAutoBankGoldCharacterExcluded(characterKey, excluded)
    end, GetExcludedCharactersText, {
        onDelete = function(characterKey)
            addon:DeleteKnownCharacter(characterKey)
        end,
    })
    excludeDropdown:SetPoint("TOPLEFT", excludeLabel, "BOTTOMLEFT", 0, -6)

    local warboundCheckbox = UI.CreateSectionToggle(warboundSection, function()
        return warboundSettings.enabled == true
    end, function(value)
        warboundSettings.enabled = value and true or false
    end)

    local expansionVendorSection = UI.CreateSection(
        frame,
        TRANSLATE("Sell legacy items"),
        TRANSLATE("Shows a safe preview of sellable items from older expansions whenever a merchant is open.")
    )
    expansionVendorSection:SetPoint("TOPLEFT", warboundSection, "BOTTOMLEFT", 0, -12)
    expansionVendorSection:SetPoint("TOPRIGHT", warboundSection, "BOTTOMRIGHT", 0, -12)
    expansionVendorSection:SetHeight(104)

    local expansionVendorCheckbox = UI.CreateSectionToggle(expansionVendorSection, function()
        return expansionVendorSettings.enabled == true
    end, function(value)
        addon:SetExpansionVendorEnabled(value)
        expansionVendorSettings = addon:GetExpansionVendorSettings()
    end)

    local expansionVendorAnchorLabel = UI.CreateLabel(
        expansionVendorSection,
        string.format("%s:", TRANSLATE("Window position")),
        11
    )
    expansionVendorAnchorLabel:SetPoint(
        "TOPLEFT",
        expansionVendorSection.description,
        "BOTTOMLEFT",
        0,
        -10
    )
    expansionVendorAnchorLabel:SetTextColor(0.78, 0.78, 0.78)

    local expansionVendorAnchorDropdown = UI.CreateDropdown(
        expansionVendorSection,
        106,
        EXPANSION_VENDOR_ANCHOR_OPTIONS,
        function()
            return addon:GetExpansionVendorAnchorSide()
        end,
        function(value)
            addon:SetExpansionVendorAnchorSide(value)
        end
    )
    expansionVendorAnchorDropdown:SetPoint(
        "LEFT",
        expansionVendorAnchorLabel,
        "RIGHT",
        -10,
        0
    )

    RefreshTargetState()

    return frame
end)
