local _, ns = ...
local MythicTools = ns.MythicTools
local UI = ns.UI

local ApplyThinScrollBar = UI.ApplyThinScrollBar
local COLORS = UI.COLORS
local COMPACT_STATS_DAMAGE_X = UI.COMPACT_STATS_DAMAGE_X
local COMPACT_STATS_DEATHS_X = UI.COMPACT_STATS_DEATHS_X
local COMPACT_STATS_DPS_X = UI.COMPACT_STATS_DPS_X
local COMPACT_STATS_HEALING_X = UI.COMPACT_STATS_HEALING_X
local COMPACT_STATS_HPS_X = UI.COMPACT_STATS_HPS_X
local COMPACT_STATS_INTERRUPTS_X = UI.COMPACT_STATS_INTERRUPTS_X
local COMPACT_STATS_ITEMS_X = UI.COMPACT_STATS_ITEMS_X
local COMPACT_STATS_SCORE_X = UI.COMPACT_STATS_SCORE_X
local COMPLETION_ROW_HEIGHT = UI.COMPLETION_ROW_HEIGHT
local ClipChildren = UI.ClipChildren
local CreateAceDropdownWidget = UI.CreateAceDropdownWidget
local CreateAceEditWidget = UI.CreateAceEditWidget
local CreateAceFlowRow = UI.CreateAceFlowRow
local CreateAceSpacer = UI.CreateAceSpacer
local CreateActionButton = UI.CreateActionButton
local CreateFont = UI.CreateFont
local CreateListButton = UI.CreateListButton
local CreateStatRow = UI.CreateStatRow
local GetDefaultSeason = UI.GetDefaultSeason
local GetDungeonOptionsForSeason = UI.GetDungeonOptionsForSeason
local GetOwnedCharacterFilterOptions = UI.GetOwnedCharacterFilterOptions
local RUN_ROWS = UI.RUN_ROWS
local RUN_ROW_HEIGHT = UI.RUN_ROW_HEIGHT
local SEASON_OPTIONS = UI.SEASON_OPTIONS
local STATUS_OPTIONS = UI.STATUS_OPTIONS
local SetAceDropdownValue = UI.SetAceDropdownValue
local SetAceEditText = UI.SetAceEditText
local StyleAceDropdownWidget = UI.StyleAceDropdownWidget
local StyleAceEditWidget = UI.StyleAceEditWidget
local UpdateAceDropdownOptions = UI.UpdateAceDropdownOptions
local WHITE_TEXTURE = UI.WHITE_TEXTURE

function MythicTools:BuildRunsPage(parent)
    local page = CreateFrame("Frame", nil, parent)
    page:SetAllPoints(parent)
    ClipChildren(page)

    local filterBar = CreateFrame("Frame", nil, page)
    filterBar:SetPoint("TOPLEFT", 12, -12)
    filterBar:SetPoint("TOPRIGHT", -12, -12)
    filterBar:SetHeight(154)
    self:ApplySurface(filterBar, COLORS.sectionBG, COLORS.surface, COLORS.accentSoft)
    self.ui.runsFilterBar = filterBar

    local filterTitle = CreateFont(filterBar, 13, COLORS.text)
    filterTitle:SetPoint("TOPLEFT", 16, -14)
    filterTitle:SetText(self:L("UI_FILTERS"))

    self.ui.runCountLabel = CreateFont(filterBar, 12, COLORS.muted, "RIGHT")
    self.ui.runCountLabel:SetPoint("TOPRIGHT", -16, -14)

    local topRow = CreateAceFlowRow(filterBar, -34, 54)
    local bottomRow = CreateAceFlowRow(filterBar, -92, 54)

    self.ui.runsSearch = CreateAceEditWidget(self:L("UI_SEARCH"), 210, self.db.ui.filters.search, function(value)
        self.db.ui.filters.search = value or ""
        self:SetRunViewMode("list")
        self:QueueRefreshRunView()
    end)
    StyleAceEditWidget(self.ui.runsSearch)
    topRow:AddChild(self.ui.runsSearch)
    topRow:AddChild(CreateAceSpacer(10))

    self.ui.runsPlayerFilter = CreateAceEditWidget(self:L("UI_PLAYER"), 190, self.db.ui.filters.player, function(value)
        self.db.ui.filters.player = value or ""
        self:SetRunViewMode("list")
        self:QueueRefreshRunView()
    end)
    StyleAceEditWidget(self.ui.runsPlayerFilter)
    topRow:AddChild(self.ui.runsPlayerFilter)
    topRow:AddChild(CreateAceSpacer(10))

    self.ui.runsDateFilter = CreateAceEditWidget(self:L("UI_DATE"), 120, self.db.ui.filters.date, function(value)
        self.db.ui.filters.date = value or ""
        self:SetRunViewMode("list")
        self:QueueRefreshRunView()
    end)
    StyleAceEditWidget(self.ui.runsDateFilter)
    topRow:AddChild(self.ui.runsDateFilter)
    topRow:AddChild(CreateAceSpacer(10))

    self.ui.runsStatusFilter = CreateAceDropdownWidget(self:L("UI_STATUS"), 140, STATUS_OPTIONS, self.db.ui.filters.status, function(value)
        self.db.ui.filters.status = value or "all"
        self:SetRunViewMode("list")
        self:RefreshRunView()
    end)
    StyleAceDropdownWidget(self.ui.runsStatusFilter)
    topRow:AddChild(self.ui.runsStatusFilter)

    self.ui.runsSeasonFilter = CreateAceDropdownWidget(self:L("UI_SEASON"), 170, SEASON_OPTIONS, self.db.ui.filters.season, function(value)
        self.db.ui.filters.season = value or SEASON_OPTIONS[1].value
        self.db.ui.filters.dungeon = "all"
        SetAceDropdownValue(self.ui.runsSeasonFilter, self.db.ui.filters.season)
        UpdateAceDropdownOptions(self.ui.runsDungeonFilter, GetDungeonOptionsForSeason(self.db.ui.filters.season), self.db.ui.filters.dungeon)
        self:SetRunViewMode("list")
        self:RefreshRunView()
    end)
    StyleAceDropdownWidget(self.ui.runsSeasonFilter)
    bottomRow:AddChild(self.ui.runsSeasonFilter)
    bottomRow:AddChild(CreateAceSpacer(10))

    self.ui.runsDungeonFilter = CreateAceDropdownWidget(self:L("UI_DUNGEON"), 260, GetDungeonOptionsForSeason(self.db.ui.filters.season), self.db.ui.filters.dungeon, function(value)
        self.db.ui.filters.dungeon = value or "all"
        self:SetRunViewMode("list")
        self:RefreshRunView()
    end)
    StyleAceDropdownWidget(self.ui.runsDungeonFilter)
    bottomRow:AddChild(self.ui.runsDungeonFilter)
    bottomRow:AddChild(CreateAceSpacer(10))

    self.ui.runsOwnedFilter = CreateAceDropdownWidget(self:L("UI_CHARACTERS"), 180, GetOwnedCharacterFilterOptions(), self.db.ui.filters.ownedCharacters or "all", function(value)
        self.db.ui.filters.ownedCharacters = value or "all"
        self:SetRunViewMode("list")
        self:RefreshRunView()
    end)
    StyleAceDropdownWidget(self.ui.runsOwnedFilter)
    bottomRow:AddChild(self.ui.runsOwnedFilter)
    bottomRow:AddChild(CreateAceSpacer(10))

    local runsClearHolder = CreateFrame("Frame", nil, filterBar)
    runsClearHolder:SetSize(86, 50)
    self.ui.runsClearButton = CreateActionButton(runsClearHolder, 86, 28, self:L("UI_CLEAR"))
    self.ui.runsClearButton:SetPoint("TOPLEFT", 0, -18)
    self:ApplyActionButtonIcon(self.ui.runsClearButton, "Interface\\AddOns\\SkyMythicHistory\\Media\\Icons\\reset.tga", 12)
    self.ui.runsClearButton:SetScript("OnClick", function()
        self.db.ui.filters.search = ""
        self.db.ui.filters.player = ""
        self.db.ui.filters.dungeon = "all"
        self.db.ui.filters.season = GetDefaultSeason()
        self.db.ui.filters.date = ""
        self.db.ui.filters.status = "all"
        self.db.ui.filters.ownedCharacters = "all"
        SetAceEditText(self.ui.runsSearch, "")
        SetAceEditText(self.ui.runsPlayerFilter, "")
        SetAceEditText(self.ui.runsDateFilter, "")
        SetAceDropdownValue(self.ui.runsSeasonFilter, GetDefaultSeason())
        UpdateAceDropdownOptions(self.ui.runsDungeonFilter, GetDungeonOptionsForSeason(GetDefaultSeason()), "all")
        SetAceDropdownValue(self.ui.runsStatusFilter, "all")
        SetAceDropdownValue(self.ui.runsOwnedFilter, "all")
        self:SetRunViewMode("list")
        self:RefreshRunView()
    end)
    bottomRow:AddChild(runsClearHolder)
    bottomRow:AddChild(CreateAceSpacer(10))

    local runsExportHolder = CreateFrame("Frame", nil, filterBar)
    runsExportHolder:SetSize(110, 50)
    self.ui.runsExportButton = CreateActionButton(runsExportHolder, 110, 28, self:L("UI_EXPORT"))
    self.ui.runsExportButton:SetPoint("TOPLEFT", 0, -18)
    self:ApplyActionButtonIcon(self.ui.runsExportButton, "Interface\\AddOns\\SkyMythicHistory\\Media\\Icons\\export.tga", 12)
    self.ui.runsExportButton:SetScript("OnClick", function()
        self:ShowCSVExportPopup()
    end)
    bottomRow:AddChild(runsExportHolder)

    local listView = CreateFrame("Frame", nil, page)
    listView:SetPoint("TOPLEFT", filterBar, "BOTTOMLEFT", 0, -12)
    listView:SetPoint("BOTTOMRIGHT", page, "BOTTOMRIGHT", -12, 12)
    self:ApplySurface(listView, COLORS.sectionBG, COLORS.surface, COLORS.accentSoft)
    ClipChildren(listView)
    self.ui.runsListView = listView

    local listTitle = CreateFont(listView, 14, COLORS.text)
    listTitle:SetPoint("TOPLEFT", 16, -14)
    listTitle:SetText(self:L("UI_KEY_HISTORY"))

    self.ui.runsEmptyState = CreateFont(listView, 13, COLORS.muted, "CENTER")
    self.ui.runsEmptyState:SetPoint("CENTER")
    self.ui.runsEmptyState:SetText(self:L("UI_NO_RUNS_MATCH"))
    self.ui.runsEmptyState:Hide()

    local listBody = CreateFrame("Frame", nil, listView)
    listBody:SetPoint("TOPLEFT", 10, -44)
    listBody:SetPoint("TOPRIGHT", -22, -44)
    listBody:SetHeight(RUN_ROWS * RUN_ROW_HEIGHT + 2)
    ClipChildren(listBody)
    self.ui.runsListBody = listBody

    self.ui.runsScroll = CreateFrame("ScrollFrame", nil, listView, "FauxScrollFrameTemplate")
    self.ui.runsScroll:SetPoint("TOPLEFT", 0, -44)
    self.ui.runsScroll:SetPoint("BOTTOMRIGHT", -10, 14)
    self.ui.runsScroll:SetScript("OnVerticalScroll", function(scrollFrame, offset)
        FauxScrollFrame_OnVerticalScroll(scrollFrame, offset, RUN_ROW_HEIGHT, function()
            self:RefreshRunView()
        end)
    end)
    ApplyThinScrollBar(self.ui.runsScroll)

    self.ui.runRows = {}
    for index = 1, RUN_ROWS do
        local row = CreateListButton(listBody, RUN_ROW_HEIGHT - 4)
        row:SetPoint("TOPLEFT", 0, -((index - 1) * RUN_ROW_HEIGHT))
        row:SetPoint("TOPRIGHT", 0, -((index - 1) * RUN_ROW_HEIGHT))
        row:SetScript("OnClick", function(button, mouseButton)
            if not button.runId then
                return
            end

            if mouseButton == "RightButton" then
                self:ConfirmDeleteRun(button.runId)
            else
                self.db.ui.selectedRunId = button.runId
                self:RefreshRunView()
                self:ShowCompletionPopup(button.runId)
            end
        end)
        self.ui.runRows[index] = row
    end

    local detailPanel = CreateFrame("Frame", nil, page)
    detailPanel:SetPoint("TOPLEFT", page, "TOPLEFT", 12, -12)
    detailPanel:SetPoint("BOTTOMRIGHT", page, "BOTTOMRIGHT", -12, 12)
    self:ApplySurface(detailPanel, COLORS.sectionBG, COLORS.surface, COLORS.accentSoft)
    ClipChildren(detailPanel)
    self.ui.runsDetailView = detailPanel

    local detailHeader = CreateFrame("Frame", nil, detailPanel)
    detailHeader:SetPoint("TOPLEFT", 16, -16)
    detailHeader:SetPoint("TOPRIGHT", -16, -16)
    detailHeader:SetHeight(38)

    self.ui.runDetailBackButton = CreateActionButton(detailHeader, 136, 28, self:L("UI_BACK_TO_HISTORY"))
    self.ui.runDetailBackButton:SetPoint("LEFT", 0, 0)
    self:ApplyActionButtonIcon(self.ui.runDetailBackButton, "Interface\\AddOns\\SkyMythicHistory\\Media\\Icons\\left.tga", 12)
    self.ui.runDetailBackButton:SetScript("OnClick", function()
        self:SetRunViewMode("list")
        self:RefreshRunView()
    end)

    local detailHeaderText = CreateFont(detailHeader, 12, COLORS.muted)
    detailHeaderText:SetPoint("LEFT", self.ui.runDetailBackButton, "RIGHT", 14, 0)
    detailHeaderText:SetText(self:L("UI_RUN_DETAILS"))

    local hero = CreateFrame("Frame", nil, detailPanel)
    hero:SetPoint("TOPLEFT", 16, -62)
    hero:SetPoint("TOPRIGHT", -16, -62)
    hero:SetHeight(150)
    self:ApplySurface(hero, COLORS.headerBG, COLORS.surface, COLORS.accent)
    self.ui.runHero = hero

    hero.Background = hero:CreateTexture(nil, "BACKGROUND")
    hero.Background:SetAllPoints()
    hero.Background:SetAlpha(0.18)
    self.ui.runHeroBackground = hero.Background

    hero.Shade = hero:CreateTexture(nil, "BORDER")
    hero.Shade:SetAllPoints()
    hero.Shade:SetTexture(WHITE_TEXTURE)
    hero.Shade:SetVertexColor(0.01, 0.02, 0.03, 0.44)

    local iconFrame = CreateFrame("Frame", nil, hero)
    iconFrame:SetSize(70, 70)
    iconFrame:SetPoint("TOPLEFT", 18, -18)
    self:ApplySurface(iconFrame, COLORS.frameBG, COLORS.accentSoft, COLORS.accent)

    iconFrame.Icon = iconFrame:CreateTexture(nil, "ARTWORK")
    iconFrame.Icon:SetPoint("TOPLEFT", 1, -1)
    iconFrame.Icon:SetPoint("BOTTOMRIGHT", -1, 1)
    self.ui.runHeroIcon = iconFrame.Icon

    self.ui.runDetailTitle = CreateFont(hero, 22, COLORS.text)
    self.ui.runDetailTitle:SetPoint("TOPLEFT", iconFrame, "TOPRIGHT", 14, -2)
    self.ui.runDetailTitle:SetPoint("RIGHT", hero, "RIGHT", -122, 0)

    self.ui.runDetailMeta = CreateFont(hero, 12, COLORS.muted)
    self.ui.runDetailMeta:SetPoint("TOPLEFT", self.ui.runDetailTitle, "BOTTOMLEFT", 0, -8)

    self.ui.runDetailSubmeta = CreateFont(hero, 11, COLORS.muted)
    self.ui.runDetailSubmeta:SetPoint("TOPLEFT", self.ui.runDetailMeta, "BOTTOMLEFT", 0, -6)
    self.ui.runDetailSubmeta:SetPoint("RIGHT", hero, "RIGHT", -16, 0)

    self.ui.runDetailStatus = CreateFont(hero, 14, COLORS.accent, "RIGHT")
    self.ui.runDetailStatus:SetPoint("TOPRIGHT", -18, -20)

    self.ui.runDetailLoot = CreateFont(hero, 11, COLORS.text)
    self.ui.runDetailLoot:SetPoint("TOPLEFT", iconFrame, "BOTTOMLEFT", 0, -10)
    self.ui.runDetailLoot:SetPoint("RIGHT", hero, "RIGHT", -18, 0)

    self.ui.runDetailNote = CreateFont(hero, 10, COLORS.subdued)
    self.ui.runDetailNote:SetPoint("TOPLEFT", self.ui.runDetailLoot, "BOTTOMLEFT", 0, -6)
    self.ui.runDetailNote:SetPoint("RIGHT", hero, "RIGHT", -18, 0)
    self.ui.runDetailNote:SetJustifyH("LEFT")

    local statsPanel = CreateFrame("Frame", nil, detailPanel)
    statsPanel:SetPoint("TOPLEFT", hero, "BOTTOMLEFT", 0, -10)
    statsPanel:SetPoint("BOTTOMRIGHT", detailPanel, "BOTTOMRIGHT", -16, 16)
    self:ApplySurface(statsPanel, COLORS.panelBG, COLORS.surface, nil)
    ClipChildren(statsPanel)

    local columnName = CreateFont(statsPanel, 11, COLORS.subdued)
    columnName:SetPoint("TOPLEFT", 16, -12)
    columnName:SetText(self:L("UI_PLAYER"))

    local columnScore = CreateFont(statsPanel, 11, COLORS.subdued)
    columnScore:SetPoint("TOPLEFT", COMPACT_STATS_SCORE_X, -12)
    columnScore:SetText(self:L("UI_SCORE"))

    local columnItems = CreateFont(statsPanel, 11, COLORS.subdued)
    columnItems:SetPoint("TOPLEFT", COMPACT_STATS_ITEMS_X, -12)
    columnItems:SetText(self:L("UI_LOOT"))

    local columnDamage = CreateFont(statsPanel, 11, COLORS.subdued)
    columnDamage:SetPoint("TOPLEFT", COMPACT_STATS_DAMAGE_X, -12)
    columnDamage:SetText(self:L("UI_DAMAGE"))

    local columnDPS = CreateFont(statsPanel, 11, COLORS.subdued)
    columnDPS:SetPoint("TOPLEFT", COMPACT_STATS_DPS_X, -12)
    columnDPS:SetText(self:L("UI_DPS"))

    local columnHealing = CreateFont(statsPanel, 11, COLORS.subdued)
    columnHealing:SetPoint("TOPLEFT", COMPACT_STATS_HEALING_X, -12)
    columnHealing:SetText(self:L("UI_HEALING"))

    local columnHPS = CreateFont(statsPanel, 11, COLORS.subdued)
    columnHPS:SetPoint("TOPLEFT", COMPACT_STATS_HPS_X, -12)
    columnHPS:SetText(self:L("UI_HPS"))

    local columnInterrupts = CreateFont(statsPanel, 11, COLORS.subdued)
    columnInterrupts:SetPoint("TOPLEFT", COMPACT_STATS_INTERRUPTS_X, -12)
    columnInterrupts:SetText(self:L("UI_INTERRUPTS"))

    local columnDeaths = CreateFont(statsPanel, 11, COLORS.subdued)
    columnDeaths:SetPoint("TOPLEFT", COMPACT_STATS_DEATHS_X, -12)
    columnDeaths:SetText(self:L("UI_DEATHS"))

    self.ui.runStatRows = {}
    for index = 1, 5 do
        local row = CreateStatRow(statsPanel)
        row:SetPoint("TOPLEFT", 12, -34 - ((index - 1) * COMPLETION_ROW_HEIGHT))
        row:SetPoint("TOPRIGHT", -12, -34 - ((index - 1) * COMPLETION_ROW_HEIGHT))
        self.ui.runStatRows[index] = row
    end

    return page
end
