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

local ApplyThinScrollBarToST = UI.ApplyThinScrollBarToST
local COLORS = UI.COLORS
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 CreateMetricCard = UI.CreateMetricCard
local CreatePortraitWidget = UI.CreatePortraitWidget
local CreateSpecChip = UI.CreateSpecChip
local GetDefaultSeason = UI.GetDefaultSeason
local GetDungeonOptionsForSeason = UI.GetDungeonOptionsForSeason
local PLAYER_DETAIL_CONTENT_HEIGHT = UI.PLAYER_DETAIL_CONTENT_HEIGHT
local PLAYER_DETAIL_HERO_HEIGHT = UI.PLAYER_DETAIL_HERO_HEIGHT
local PLAYER_DETAIL_HISTORY_HEIGHT = UI.PLAYER_DETAIL_HISTORY_HEIGHT
local PLAYER_DETAIL_NOTE_HEIGHT = UI.PLAYER_DETAIL_NOTE_HEIGHT
local PLAYER_DETAIL_SPEC_CHIPS = UI.PLAYER_DETAIL_SPEC_CHIPS
local SEASON_OPTIONS = UI.SEASON_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
local floor = UI.floor
local max = UI.max
local min = UI.min

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

    local indexView = CreateFrame("Frame", nil, page)
    indexView:SetAllPoints(page)
    ClipChildren(indexView)
    self.ui.playersIndexView = indexView

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

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

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

    local filtersRow = CreateAceFlowRow(filterBar, -34, 54)

    self.ui.playerSearch = CreateAceEditWidget(self:L("UI_SEARCH_PLAYER"), 280, (self.db.ui.playerFilters and self.db.ui.playerFilters.search) or "", function(value)
        self.db.ui.playerFilters.search = value or ""
        self.db.ui.playerSearch = value or ""
        self:QueueRefreshPlayersView()
    end)
    StyleAceEditWidget(self.ui.playerSearch)
    filtersRow:AddChild(self.ui.playerSearch)
    filtersRow:AddChild(CreateAceSpacer(10))

    self.ui.playersSeasonFilter = CreateAceDropdownWidget(self:L("UI_SEASON"), 170, SEASON_OPTIONS, (self.db.ui.playerFilters and self.db.ui.playerFilters.season) or GetDefaultSeason(), function(value)
        self.db.ui.playerFilters.season = value or GetDefaultSeason()
        self.db.ui.playerFilters.dungeon = "all"
        SetAceDropdownValue(self.ui.playersSeasonFilter, self.db.ui.playerFilters.season)
        UpdateAceDropdownOptions(self.ui.playersDungeonFilter, GetDungeonOptionsForSeason(self.db.ui.playerFilters.season), self.db.ui.playerFilters.dungeon)
        self:RefreshPlayersView()
    end)
    StyleAceDropdownWidget(self.ui.playersSeasonFilter)
    filtersRow:AddChild(self.ui.playersSeasonFilter)
    filtersRow:AddChild(CreateAceSpacer(10))

    self.ui.playersDungeonFilter = CreateAceDropdownWidget(self:L("UI_DUNGEON"), 260, GetDungeonOptionsForSeason((self.db.ui.playerFilters and self.db.ui.playerFilters.season) or GetDefaultSeason()), (self.db.ui.playerFilters and self.db.ui.playerFilters.dungeon) or "all", function(value)
        self.db.ui.playerFilters.dungeon = value or "all"
        self:RefreshPlayersView()
    end)
    StyleAceDropdownWidget(self.ui.playersDungeonFilter)
    filtersRow:AddChild(self.ui.playersDungeonFilter)
    filtersRow:AddChild(CreateAceSpacer(10))

    self.ui.playersAugFilter = CreateAceDropdownWidget("Aug", 130, {
        {value = "all", label = "All groups"},
        {value = "no_aug", label = "No aug"},
    }, (self.db.ui.playerFilters and self.db.ui.playerFilters.augMode) or "all", function(value)
        self.db.ui.playerFilters.augMode = value or "all"
        SetAceDropdownValue(self.ui.playersAugFilter, self.db.ui.playerFilters.augMode)
        self:RefreshPlayersView()
    end)
    StyleAceDropdownWidget(self.ui.playersAugFilter)
    filtersRow:AddChild(self.ui.playersAugFilter)

    self.ui.playersClearFiltersButton = CreateActionButton(filterBar, 104, 28, self:L("UI_CLEAR"))
    self.ui.playersClearFiltersButton:SetPoint("TOPRIGHT", -16, -52)
    self:ApplyActionButtonIcon(self.ui.playersClearFiltersButton, "Interface\\AddOns\\SkyMythicHistory\\Media\\Icons\\reset.tga", 12)
    self.ui.playersClearFiltersButton:SetScript("OnClick", function()
        self.db.ui.playerFilters.search = ""
        self.db.ui.playerFilters.season = GetDefaultSeason()
        self.db.ui.playerFilters.dungeon = "all"
        self.db.ui.playerFilters.augMode = "all"
        self.db.ui.playerSearch = ""
        SetAceEditText(self.ui.playerSearch, "")
        SetAceDropdownValue(self.ui.playersSeasonFilter, GetDefaultSeason())
        UpdateAceDropdownOptions(self.ui.playersDungeonFilter, GetDungeonOptionsForSeason(GetDefaultSeason()), "all")
        SetAceDropdownValue(self.ui.playersAugFilter, "all")
        self:RefreshPlayersView()
    end)

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

    local tableTitle = CreateFont(tableCard, 14, COLORS.text)
    tableTitle:SetPoint("TOPLEFT", 16, -14)
    tableTitle:SetText(self:L("UI_PLAYER_ANALYTICS"))

    self.ui.playersEmptyState = CreateFont(tableCard, 13, COLORS.muted, "CENTER")
    self.ui.playersEmptyState:SetPoint("CENTER")
    self.ui.playersEmptyState:SetText(self:L("UI_NO_PLAYERS_MATCH"))
    self.ui.playersEmptyState:Hide()

    self.ui.playersTableCard = tableCard
    self.ui.playersTable = self:CreatePlayersAnalyticsTable(tableCard)
    if self.ui.playersTable then
        ApplyThinScrollBarToST(self.ui.playersTable)
    end

    local detailView = CreateFrame("Frame", nil, page)
    detailView:SetAllPoints(page)
    ClipChildren(detailView)
    self.ui.playersDetailView = detailView

    self.ui.playerDetailBackButton = CreateActionButton(detailView, 138, 28, self:L("UI_BACK_TO_PLAYERS"))
    self.ui.playerDetailBackButton:SetPoint("TOPLEFT", 12, -12)
    self:ApplyActionButtonIcon(self.ui.playerDetailBackButton, "Interface\\AddOns\\SkyMythicHistory\\Media\\Icons\\left.tga", 12)
    self.ui.playerDetailBackButton:SetScript("OnClick", function()
        MythicTools:ShowPlayersIndex()
    end)

    self.ui.playerDetailRaiderIOButton = CreateActionButton(detailView, 132, 28, self:L("PLAYER_CONTEXT_COPY_RAIDERIO"))
    self.ui.playerDetailRaiderIOButton:SetPoint("LEFT", self.ui.playerDetailBackButton, "RIGHT", 12, 0)
    self:ApplyActionButtonIcon(self.ui.playerDetailRaiderIOButton, "Interface\\AddOns\\SkyMythicHistory\\Media\\Icons\\copy.tga", 12)
    self.ui.playerDetailRaiderIOButton:SetScript("OnClick", function(button)
        MythicTools:ShowRaiderIOCopyPopup(button.playerName or (MythicTools.db and MythicTools.db.ui and MythicTools.db.ui.selectedPlayer))
    end)

    self.ui.playerDetailHeader = CreateFont(detailView, 12, COLORS.muted)
    self.ui.playerDetailHeader:SetPoint("LEFT", self.ui.playerDetailRaiderIOButton, "RIGHT", 14, 0)
    self.ui.playerDetailHeader:SetText(self:L("UI_PLAYER_DETAILS"))

    local detailScrollFrame = CreateFrame("ScrollFrame", nil, detailView)
    detailScrollFrame:SetPoint("TOPLEFT", 12, -52)
    detailScrollFrame:SetPoint("BOTTOMRIGHT", -20, 12)
    detailScrollFrame:EnableMouseWheel(true)
    self.ui.playerDetailScrollFrame = detailScrollFrame

    local frameW = (self.db and self.db.ui and self.db.ui.width) or 1280
    local detailScrollW = max(760, frameW - 245)
    local detailContent = CreateFrame("Frame", nil, detailScrollFrame)
    detailContent:SetSize(detailScrollW, PLAYER_DETAIL_CONTENT_HEIGHT)
    detailScrollFrame:SetScrollChild(detailContent)
    self.ui.playerDetailContent = detailContent

    local detailScrollBar = CreateFrame("Slider", nil, detailView)
    detailScrollBar:SetOrientation("VERTICAL")
    detailScrollBar:SetWidth(6)
    detailScrollBar:SetPoint("TOPRIGHT", detailView, "TOPRIGHT", -12, -52)
    detailScrollBar:SetPoint("BOTTOMRIGHT", detailView, "BOTTOMRIGHT", -12, 12)
    detailScrollBar:SetMinMaxValues(0, 1)
    detailScrollBar:SetValue(0)
    detailScrollBar:Hide()
    local detailThumb = detailScrollBar:CreateTexture(nil, "ARTWORK")
    detailThumb:SetTexture(WHITE_TEXTURE)
    detailThumb:SetWidth(4)
    detailThumb:SetVertexColor(COLORS.accent[1], COLORS.accent[2], COLORS.accent[3], 0.65)
    detailScrollBar:SetThumbTexture(detailThumb)
    detailScrollBar:SetScript("OnValueChanged", function(_, value)
        detailScrollFrame:SetVerticalScroll(value)
    end)
    detailScrollFrame:SetScript("OnScrollRangeChanged", function(_, _, yRange)
        local range = max(0, yRange or 0)
        detailScrollBar:SetMinMaxValues(0, range)
        detailScrollBar:SetShown(range > 0)
    end)
    detailScrollFrame:SetScript("OnMouseWheel", function(_, delta)
        local current = detailScrollBar:GetValue()
        local _, maxValue = detailScrollBar:GetMinMaxValues()
        detailScrollBar:SetValue(max(0, min(current - delta * 60, maxValue)))
    end)
    self.ui.playerDetailScrollBar = detailScrollBar

    local heroCard = CreateFrame("Frame", nil, detailContent)
    heroCard:SetPoint("TOPLEFT", detailContent, "TOPLEFT", 0, 0)
    heroCard:SetSize(detailScrollW, PLAYER_DETAIL_HERO_HEIGHT)
    self:ApplySurface(heroCard, COLORS.headerBG, COLORS.surface, COLORS.accent)
    self.ui.playerDetailHero = heroCard

    heroCard.Background = heroCard:CreateTexture(nil, "BACKGROUND")
    heroCard.Background:SetAllPoints()
    heroCard.Background:SetAlpha(0.18)

    self.ui.playerDetailPortrait = CreatePortraitWidget(heroCard, 82, {noBorder = true})
    self.ui.playerDetailPortrait:SetPoint("TOPLEFT", 16, -10)

    self.ui.playerDetailRatingBadge = self:CreateHeroRatingBadge(heroCard)
    self.ui.playerDetailRatingBadge:SetPoint("TOPRIGHT", -18, -18)

    self.ui.playerDetailName = CreateFont(heroCard, 22, COLORS.text)
    self.ui.playerDetailName:SetPoint("TOPLEFT", self.ui.playerDetailPortrait, "TOPRIGHT", 16, -8)
    self.ui.playerDetailName:SetPoint("TOPRIGHT", self.ui.playerDetailRatingBadge, "TOPLEFT", -12, 0)

    self.ui.playerDetailRealm = CreateFont(heroCard, 12, COLORS.accentSoft)
    self.ui.playerDetailRealm:SetPoint("TOPLEFT", self.ui.playerDetailName, "BOTTOMLEFT", 0, -6)
    self.ui.playerDetailRealm:SetPoint("TOPRIGHT", self.ui.playerDetailRatingBadge, "BOTTOMLEFT", -12, -6)
    self.ui.playerDetailRealm:SetJustifyH("LEFT")

    self.ui.playerDetailMeta = CreateFont(heroCard, 11, COLORS.muted)
    self.ui.playerDetailMeta:SetPoint("TOPLEFT", self.ui.playerDetailRealm, "BOTTOMLEFT", 0, -6)
    self.ui.playerDetailMeta:SetPoint("TOPRIGHT", heroCard, "TOPRIGHT", -52, -74)
    self.ui.playerDetailMeta:SetJustifyH("LEFT")

    self.ui.playerDetailSummaryPrimary = CreateFont(heroCard, 11, COLORS.text)
    self.ui.playerDetailSummaryPrimary:SetPoint("TOPLEFT", self.ui.playerDetailMeta, "BOTTOMLEFT", 0, -8)
    self.ui.playerDetailSummaryPrimary:SetPoint("TOPRIGHT", heroCard, "TOPRIGHT", -18, -68)
    self.ui.playerDetailSummaryPrimary:SetJustifyH("LEFT")
    self.ui.playerDetailSummaryPrimary:SetJustifyV("TOP")
    self.ui.playerDetailSummaryPrimary:Hide()

    self.ui.playerDetailSummarySecondary = CreateFont(heroCard, 11, COLORS.muted)
    self.ui.playerDetailSummarySecondary:SetPoint("TOPLEFT", self.ui.playerDetailSummaryPrimary, "BOTTOMLEFT", 0, -6)
    self.ui.playerDetailSummarySecondary:SetPoint("TOPRIGHT", heroCard, "TOPRIGHT", -18, -88)
    self.ui.playerDetailSummarySecondary:SetJustifyH("LEFT")
    self.ui.playerDetailSummarySecondary:SetJustifyV("TOP")
    self.ui.playerDetailSummarySecondary:Hide()

    self.ui.playerDetailHeroNote = CreateFont(heroCard, 10, COLORS.subdued)
    self.ui.playerDetailHeroNote:SetPoint("TOPLEFT", self.ui.playerDetailMeta, "BOTTOMLEFT", 0, -6)
    self.ui.playerDetailHeroNote:SetPoint("TOPRIGHT", heroCard, "TOPRIGHT", -18, -94)
    self.ui.playerDetailHeroNote:SetJustifyH("LEFT")
    self.ui.playerDetailHeroNote:SetJustifyV("TOP")

    local metricSpecs = {
        {key = "runs", label = "Runs"},
        {key = "timed", label = "Timed"},
        {key = "bestKey", label = "Best Key"},
        {key = "avgKey", label = "Avg Key"},
        {key = "maxDps", label = "Max DPS"},
        {key = "avgDps", label = "Avg DPS"},
        {key = "maxHps", label = "Max HPS"},
        {key = "avgHps", label = "Avg HPS"},
    }
    self.ui.playerDetailMetricCards = {}
    local metricGap = 8
    local metricCardW = floor((detailScrollW - 36 - (3 * metricGap)) / 4)
    for index, spec in ipairs(metricSpecs) do
        local card = CreateMetricCard(heroCard, spec.label)
        card:SetSize(metricCardW, 58)
        local column = (index - 1) % 4
        local row = floor((index - 1) / 4)
        card:SetPoint("TOPLEFT", heroCard, "TOPLEFT", 18 + (column * (metricCardW + metricGap)), -104 - (row * 66))
        self.ui.playerDetailMetricCards[spec.key] = card
    end

    self.ui.playerDetailNoteIndicator = CreateFont(heroCard, 10, COLORS.accentSoft, "RIGHT")
    self.ui.playerDetailNoteIndicator:SetPoint("BOTTOMRIGHT", heroCard, "BOTTOMRIGHT", -18, 14)
    self.ui.playerDetailNoteIndicator:Hide()

    local chipsLabel = CreateFont(heroCard, 10, COLORS.subdued)
    chipsLabel:SetPoint("BOTTOMLEFT", heroCard, "BOTTOMLEFT", 108, 14)
    chipsLabel:SetText("")
    chipsLabel:Hide()

    local chipsContainer = CreateFrame("Frame", nil, heroCard)
    chipsContainer:SetPoint("BOTTOMRIGHT", heroCard, "BOTTOMRIGHT", -18, 12)
    chipsContainer:SetSize(0, 26)
    self.ui.playerDetailSpecChipsContainer = chipsContainer

    self.ui.playerDetailSpecChips = {}
    for index = 1, PLAYER_DETAIL_SPEC_CHIPS do
        local chip = CreateSpecChip(chipsContainer)
        chip:Hide()
        self.ui.playerDetailSpecChips[index] = chip
    end

    self.ui.playerDetailSpecChipEmpty = CreateFont(heroCard, 10, COLORS.subdued)
    self.ui.playerDetailSpecChipEmpty:SetPoint("LEFT", chipsContainer, "LEFT", 0, 0)
    self.ui.playerDetailSpecChipEmpty:SetText("")
    self.ui.playerDetailSpecChipEmpty:Hide()

    local noteCard = CreateFrame("Frame", nil, detailContent)
    noteCard:SetPoint("TOPLEFT", heroCard, "BOTTOMLEFT", 0, -12)
    noteCard:SetSize(detailScrollW, PLAYER_DETAIL_NOTE_HEIGHT)
    self:ApplySurface(noteCard, COLORS.sectionBG, COLORS.surface, COLORS.accentSoft)
    self.ui.playerDetailNoteCard = noteCard

    local noteTitle = CreateFont(noteCard, 13, COLORS.text)
    noteTitle:SetPoint("TOPLEFT", 16, -14)
    noteTitle:SetText(self:L("UI_NOTE"))

    local noteHint = CreateFont(noteCard, 10, COLORS.subdued)
    noteHint:SetPoint("LEFT", noteTitle, "RIGHT", 10, 0)
    noteHint:SetText("")
    noteHint:Hide()
    self.ui.playerDetailNoteHint = noteHint

    self.ui.playerDetailNoteEdit = CreateActionButton(noteCard, 126, 26, self:L("UI_ADD_NOTE"))
    self.ui.playerDetailNoteEdit:SetPoint("TOPRIGHT", -16, -10)
    self:ApplyActionButtonIcon(self.ui.playerDetailNoteEdit, "Interface\\AddOns\\SkyMythicHistory\\Media\\Icons\\add.tga", 11)
    self.ui.playerDetailNoteEdit:SetScript("OnClick", function(button)
        MythicTools:ShowPlayerNoteEditor(button.playerName or (MythicTools.db and MythicTools.db.ui and MythicTools.db.ui.selectedPlayer))
    end)

    self.ui.playerDetailNoteText = CreateFont(noteCard, 12, COLORS.text)
    self.ui.playerDetailNoteText:SetPoint("TOPLEFT", 16, -38)
    self.ui.playerDetailNoteText:SetPoint("TOPRIGHT", noteCard, "TOPRIGHT", -160, -38)
    self.ui.playerDetailNoteText:SetHeight(54)
    self.ui.playerDetailNoteText:SetJustifyH("LEFT")
    self.ui.playerDetailNoteText:SetJustifyV("TOP")
    if self.ui.playerDetailNoteText.SetWordWrap then
        self.ui.playerDetailNoteText:SetWordWrap(true)
    end

    self.ui.playerDetailNoteStatus = CreateFont(noteCard, 10, COLORS.subdued)
    self.ui.playerDetailNoteStatus:SetPoint("BOTTOMLEFT", 16, 12)
    self.ui.playerDetailNoteStatus:SetText("")
    self.ui.playerDetailNoteStatus:Hide()

    local historyCard = CreateFrame("Frame", nil, detailContent)
    historyCard:SetPoint("TOPLEFT", noteCard, "BOTTOMLEFT", 0, -12)
    historyCard:SetSize(detailScrollW, PLAYER_DETAIL_HISTORY_HEIGHT)
    self:ApplySurface(historyCard, COLORS.sectionBG, COLORS.surface, COLORS.accentSoft)
    ClipChildren(historyCard)
    self.ui.playerDetailHistoryCard = historyCard

    local historyTitle = CreateFont(historyCard, 13, COLORS.text)
    historyTitle:SetPoint("TOPLEFT", 16, -14)
    historyTitle:SetText(self:L("UI_RUNS_HISTORY"))

    self.ui.playerDetailHistoryCount = CreateFont(historyCard, 11, COLORS.muted, "RIGHT")
    self.ui.playerDetailHistoryCount:SetPoint("TOPRIGHT", -16, -14)

    self.ui.playerDetailRunsTable = self:CreateDetailRunsTable(historyCard, 14)

    self.ui.playerDetailEmptyHistory = CreateFont(historyCard, 12, COLORS.muted, "CENTER")
    self.ui.playerDetailEmptyHistory:SetPoint("CENTER")
    self.ui.playerDetailEmptyHistory:SetText(self:L("UI_NO_RUNS_PLAYER"))
    self.ui.playerDetailEmptyHistory:Hide()

    return page
end

