local addonName, SinsToolkit = ...

SinsToolkit.UI = SinsToolkit.UI or {}
SinsToolkit.UI.Pages = SinsToolkit.UI.Pages or {}

local PageBase = SinsToolkit.UI.Pages.Base or {}
local Helpers = SinsToolkit.UI.Pages.Helpers or {}
local Page = {}
setmetatable(Page, { __index = PageBase })
SinsToolkit.UI.Pages.Profiles = Page
Page.density = Helpers.GetDefaultDensity and Helpers.GetDefaultDensity() or "compact"

function Page:Create(CreateScrollablePage, Window, CreateWrappedText)
    local Theme = Helpers.GetTheme and Helpers.GetTheme()
    local profilesPage, content = CreateScrollablePage("Profiles")
    Helpers.CreatePageIntro(content, Window, "Profile Vault", "Save and restore character setup backups. Backups include action bars, account macros, character macros, keybinds, character name, realm, class, backup date, and your custom backup name. Restore and delete actions require confirmation.", CreateWrappedText, 720)

    local createCard = Helpers.CreatePageCard(content, "Create Backup", 704, 112)
    createCard:SetPoint("TOPLEFT", content, "TOPLEFT", 0, -92)
    Helpers.SetCardDescription(createCard, "Name this backup before saving your current action bars, macros, and keybinds.")

    local pBackupNameInput = CreateFrame("EditBox", nil, createCard, "InputBoxTemplate")
    pBackupNameInput:SetSize(220, 24)
    pBackupNameInput:SetPoint("TOPLEFT", createCard, "TOPLEFT", 18, -64)
    pBackupNameInput:SetAutoFocus(false)
    Window:SetTooltip(pBackupNameInput, "Backup Name", "Name this backup before saving your current action bars, macros, and keybinds.")

    local inputLabel = createCard:CreateFontString(nil, "OVERLAY", Theme and Theme.GetFont and Theme.GetFont("label") or "GameFontNormalSmall")
    inputLabel:SetPoint("BOTTOMLEFT", pBackupNameInput, "TOPLEFT", 0, 4)
    inputLabel:SetText("Backup Name")
    if Theme and Theme.ApplyLabelFont then Theme.ApplyLabelFont(inputLabel) end

    local pBtnCreate = Window:CreateButton(createCard, "Create Backup", 160, 30, function()
        if not SinsToolkit.ProfileVault then return end
        local name = pBackupNameInput:GetText()
        local backup = SinsToolkit.ProfileVault:CreateBackup(name)
        Window.selectedProfileVaultBackup = backup.id
        print("|cff9b59b6[Sin's Toolkit: QOL]|r Profile backup saved: " .. backup.name)
        if Window.RefreshProfilesPage then Window:RefreshProfilesPage() end
    end, "Saves this character's action bars, account macros, character macros, and keybinds into Profile Vault.")
    pBtnCreate:SetPoint("LEFT", pBackupNameInput, "RIGHT", 14, 0)

    local listCard = Helpers.ClearCardBody(Helpers.CreatePageCard(content, "Saved Backups", 328, 288))
    listCard:SetPoint("TOPLEFT", createCard, "BOTTOMLEFT", 0, -14)

    local pBackupList = CreateFrame("Frame", nil, listCard, "BackdropTemplate")
    pBackupList:SetSize(292, 224)
    pBackupList:SetPoint("TOPLEFT", listCard, "TOPLEFT", 18, -46)
    Helpers.ApplyListBackdrop(pBackupList, 0.1, 0.1, 0.1, 0.8, 0.4, 0.4, 0.4, 1)

    local pScrollFrame = CreateFrame("ScrollFrame", nil, pBackupList, "UIPanelScrollFrameTemplate")
    pScrollFrame:SetPoint("TOPLEFT", 4, -4)
    pScrollFrame:SetPoint("BOTTOMRIGHT", -26, 4)
    local pScrollChild = CreateFrame("Frame", nil, pScrollFrame)
    pScrollChild:SetSize(260, 1)
    pScrollFrame:SetScrollChild(pScrollChild)

    local detailsCard = Helpers.ClearCardBody(Helpers.CreatePageCard(content, "Backup Details", 362, 288))
    detailsCard:SetPoint("TOPLEFT", listCard, "TOPRIGHT", 14, 0)

    local pSummaryDetails = detailsCard:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    pSummaryDetails:SetPoint("TOPLEFT", detailsCard, "TOPLEFT", 18, -46)
    pSummaryDetails:SetWidth(326)
    pSummaryDetails:SetJustifyH("LEFT")
    pSummaryDetails:SetJustifyV("TOP")
    pSummaryDetails:SetText("No saved backups yet. Create a backup to store this character's current setup.")
    if Theme and Theme.ApplyStatusText then Theme.ApplyStatusText(pSummaryDetails) end

    local pBtnRestore = Window:CreateButton(detailsCard, "Restore Profile", 140, 30, function()
        if not SinsToolkit.ProfileVault or not Window.selectedProfileVaultBackup then return end
        SinsToolkit.ProfileVault:ConfirmRestoreBackup(Window.selectedProfileVaultBackup, function(ok, message)
            print("|cff9b59b6[Sin's Toolkit: QOL]|r " .. (message or (ok and "Profile restored." or "Profile restore failed.")))
        end)
    end, "Applies the selected backup to the current character after confirmation. This can replace action bars, macros, and keybindings.")
    pBtnRestore:SetPoint("BOTTOMLEFT", detailsCard, "BOTTOMLEFT", 18, 18)

    local pBtnDelete = Window:CreateButton(detailsCard, "Delete Profile", 140, 30, function()
        if not SinsToolkit.ProfileVault or not Window.selectedProfileVaultBackup then return end
        SinsToolkit.ProfileVault:ConfirmDeleteBackup(Window.selectedProfileVaultBackup, function(ok, message)
            if ok then
                Window.selectedProfileVaultBackup = nil
                if Window.RefreshProfilesPage then Window:RefreshProfilesPage() end
            end
            print("|cff9b59b6[Sin's Toolkit: QOL]|r " .. (message or (ok and "Profile backup deleted." or "Profile backup delete failed.")))
        end)
    end, "Deletes the selected backup from Sin's Toolkit saved variables after confirmation.")
    pBtnDelete:SetPoint("LEFT", pBtnRestore, "RIGHT", 10, 0)

    local profileButtons = {}
    function Window:RefreshProfilesPage()
        for _, b in ipairs(profileButtons) do b:Hide() end
        if not SinsToolkit.ProfileVault then return end
        local backups = SinsToolkit.ProfileVault:GetBackups()
        if listCard.title then
            listCard.title:SetText("Saved Backups (" .. #backups .. ")")
        end
        local y = -2
        local hasSelection = false
        for i, backup in ipairs(backups) do
            local b = profileButtons[i]
            if not b then
                b = CreateFrame("Button", nil, pScrollChild, "BackdropTemplate")
                b:SetSize(260, 24)
                b.text = b:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
                b.text:SetPoint("LEFT", 6, 0)
                b.text:SetPoint("RIGHT", -6, 0)
                b.text:SetJustifyH("LEFT")
                if Theme and Theme.ApplySmallBodyFont then Theme.ApplySmallBodyFont(b.text) end
                b:SetScript("OnClick", function(self)
                    Window.selectedProfileVaultBackup = self.backupID
                    Window:RefreshProfilesPage()
                end)
                profileButtons[i] = b
            end
            b.backupID = backup.id
            b:SetPoint("TOPLEFT", 0, y)
            local label = ("%s - %s"):format(backup.name or "Backup", backup.className or "Unknown")
            b.text:SetText(label)
            if Window.selectedProfileVaultBackup == backup.id then
                Helpers.ApplySelectionBackdrop(b)
                hasSelection = true
            else
                b:SetBackdrop(nil)
            end
            b:Show()
            y = y - 26
        end
        if not hasSelection then
            Window.selectedProfileVaultBackup = nil
        end
        pScrollChild:SetHeight(math.max(1, -y))

        if Window.selectedProfileVaultBackup then
            pSummaryDetails:SetText(SinsToolkit.ProfileVault:GetRestoreSummary(Window.selectedProfileVaultBackup) or "No details available.")
            pBtnRestore:Enable()
            pBtnDelete:Enable()
        elseif #backups == 0 then
            pSummaryDetails:SetText("No saved backups yet. Create a backup to store this character's current action bars, macros, and keybinds.")
            pBtnRestore:Disable()
            pBtnDelete:Disable()
        else
            pSummaryDetails:SetText("Select a saved backup to view its details.")
            pBtnRestore:Disable()
            pBtnDelete:Disable()
        end
    end
    profilesPage.OnShowCallback = function() Window:RefreshProfilesPage() end

    content:SetHeight(560)
    self.frame = profilesPage
    return profilesPage
end

Page:Register("Profiles")

return Page
