--[[
    Cerebro - UISandbox Loot History Tab
    Extracted from UI/UISandbox.lua (Phase 2a decomposition)

    @module UI.Tabs.LootHistory
    @version 0.12.0
]]--

local AddonName = "Cerebro"
local Cerebro = LibStub("AceAddon-3.0"):GetAddon(AddonName)
local AceGUI = LibStub("AceGUI-3.0")
local UISandbox = Cerebro:GetModule("UISandbox")

--[[=============================================
	Tab: RCLC Loot History
	3-region frame: fixed header (dropdowns + Starting GP),
	scrollable loot rows (GP + Cumulative GP columns),
	anchored End GP footer
===============================================]]

-- Filter state for Loot History tab
UISandbox.lootHistoryFilters = UISandbox.lootHistoryFilters or {
	date = nil,   -- selected date string
	player = nil, -- selected player name or nil for "All Players"
}

function UISandbox:DrawLootHistoryTab(container)
	local importModule = Cerebro:GetModule("RCLC_Import", true)
	if not importModule then
		local errLabel = AceGUI:Create("Label")
		errLabel:SetText("|cffff0000RCLC Import module not available.|r\n\nEnsure RCLootCouncil is installed.")
		errLabel:SetFullWidth(true)
		container:AddChild(errLabel)
		return
	end

	-- Detect new dates from RCLC auto-sync
	importModule:DetectNewRCLCDates()

	-- Get available dates
	local dates = importModule:GetLootDates()

	if #dates == 0 then
		local emptyLabel = AceGUI:Create("Label")
		emptyLabel:SetText("\n\n|cff666666No RCLC loot data found.\n\nLoot history will appear here after items are awarded via RCLootCouncil.|r")
		emptyLabel:SetFullWidth(true)
		container:AddChild(emptyLabel)
		return
	end

	-- Default to latest date if none selected
	local dateStillValid = false
	if self.lootHistoryFilters.date then
		for _, d in ipairs(dates) do
			if d == self.lootHistoryFilters.date then dateStillValid = true; break end
		end
	end
	if not dateStillValid then
		self.lootHistoryFilters.date = dates[1] -- Most recent
	end
	local selectedDate = self.lootHistoryFilters.date

	-- Get players for selected date
	local playersForDate = importModule:GetPlayersForDate(selectedDate)

	-- Default to current player if they have entries, otherwise "All Players"
	local myName = Cerebro:GetPlayerFullName()
	if self.lootHistoryFilters.player == nil then
		local hasMyData = false
		for _, p in ipairs(playersForDate) do
			if p == myName then hasMyData = true; break end
		end
		self.lootHistoryFilters.player = hasMyData and myName or ""
	end
	local selectedPlayer = self.lootHistoryFilters.player

	-- ================================
	-- REGION 1: Fixed Header (Dropdowns + Starting GP)
	-- ================================
	local headerGroup = AceGUI:Create("SimpleGroup")
	headerGroup:SetFullWidth(true)
	headerGroup:SetLayout("Flow")
	container:AddChild(headerGroup)

	-- Date dropdown
	local dateList = {}
	for _, d in ipairs(dates) do
		dateList[d] = d
	end

	local dateDD = AceGUI:Create("Dropdown")
	dateDD:SetLabel("")
	dateDD:SetWidth(120)
	dateDD:SetList(dateList, dates) -- Ordered by most recent first
	dateDD:SetValue(selectedDate)
	dateDD:SetCallback("OnValueChanged", function(_, _, val)
		self.lootHistoryFilters.date = val
		self.lootHistoryFilters.player = nil -- Reset player filter on date change
		self:SelectTab("loot_history")
	end)
	headerGroup:AddChild(dateDD)

	-- Name dropdown
	local nameList = {[""] = "All Players"}
	local nameOrder = {""}
	for _, p in ipairs(playersForDate) do
		local shortName = Cerebro:GetShortPlayerName(p) or p
		nameList[p] = shortName
		table.insert(nameOrder, p)
	end

	local nameDD = AceGUI:Create("Dropdown")
	nameDD:SetLabel("")
	nameDD:SetWidth(140)
	nameDD:SetList(nameList, nameOrder)
	nameDD:SetValue(selectedPlayer)
	nameDD:SetCallback("OnValueChanged", function(_, _, val)
		self.lootHistoryFilters.player = val
		self:SelectTab("loot_history")
	end)
	headerGroup:AddChild(nameDD)

	-- Get loot entries for selected date + player
	local playerFilter = (selectedPlayer ~= "") and selectedPlayer or nil
	local entries = importModule:GetLootEntries(selectedDate, playerFilter)

	-- Parse the date to a Unix timestamp for GP calculations
	local dateMonth, dateDay, dateYear = selectedDate:match("(%d+)/(%d+)/(%d+)")
	local dayTimestamp = 0
	if dateMonth and dateDay and dateYear then
		dayTimestamp = time({year = tonumber(dateYear), month = tonumber(dateMonth), day = tonumber(dateDay), hour = 0, min = 0, sec = 0})
	end

	-- Calculate Starting GP (only meaningful for single player view)
	local isSinglePlayer = (playerFilter ~= nil)
	local startingGP = 0
	if isSinglePlayer and dayTimestamp > 0 then
		startingGP = importModule:GetStartingGP(selectedPlayer, dayTimestamp)
	end

	-- Starting GP header (only shown for single player)
	if isSinglePlayer then
		local startGPLabel = AceGUI:Create("Label")
		startGPLabel:SetText(string.format("|cffFFD700Starting GP:|r |cffffffff%s|r", Cerebro:FormatNumber(startingGP)))
		startGPLabel:SetFullWidth(true)
		container:AddChild(startGPLabel)
	end

	-- ================================
	-- Column Header
	-- ================================
	local colHeaderWrapper = AceGUI:Create("SimpleGroup")
	colHeaderWrapper:SetLayout("Fill")
	colHeaderWrapper:SetFullWidth(true)
	colHeaderWrapper:SetHeight(22)
	container:AddChild(colHeaderWrapper)

	local hf = self:TrackContentFrame(CreateFrame("Frame", nil, colHeaderWrapper.frame))
	hf:SetAllPoints()

	local colName = hf:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
	colName:SetPoint("LEFT", 8, 0)
	colName:SetText("|cffFFD700Name|r")

	local colTime = hf:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
	colTime:SetPoint("LEFT", 90, 0)
	colTime:SetText("|cffFFD700Time|r")

	local colItem = hf:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
	colItem:SetPoint("LEFT", 150, 0)
	colItem:SetText("|cffFFD700Item|r")

	local colResp = hf:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
	colResp:SetPoint("LEFT", 310, 0)
	colResp:SetText("|cffFFD700Response|r")

	local colGP = hf:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
	colGP:SetPoint("RIGHT", -80, 0)
	colGP:SetText("|cffFFD700GP|r")

	if isSinglePlayer then
		local colCumGP = hf:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
		colCumGP:SetPoint("RIGHT", -10, 0)
		colCumGP:SetText("|cffFFD700Cum. GP|r")
	end

	-- ================================
	-- REGION 2: Scrollable Loot Rows
	-- ================================
	local mainGroup = AceGUI:Create("InlineGroup")
	mainGroup:SetTitle("")
	mainGroup:SetFullWidth(true)
	mainGroup:SetFullHeight(true)
	mainGroup:SetLayout("Fill")
	container:AddChild(mainGroup)

	local scroll = AceGUI:Create("ScrollFrame")
	scroll:SetLayout("Flow")
	scroll:SetFullWidth(true)
	scroll:SetFullHeight(true)
	mainGroup:AddChild(scroll)

	-- Empty state
	if #entries == 0 then
		local emptyLabel = AceGUI:Create("Label")
		emptyLabel:SetText("\n\n|cff666666No loot entries for this date" .. (playerFilter and (" for " .. Cerebro:GetShortPlayerName(playerFilter)) or "") .. ".|r")
		emptyLabel:SetFullWidth(true)
		scroll:AddChild(emptyLabel)
	else
		-- Render each loot row
		local cumulativeGP = startingGP

		for i, entry in ipairs(entries) do
			local gp = importModule:CalculateGP(entry)
			cumulativeGP = cumulativeGP + gp

			self:CreateLootHistoryRow(scroll, entry, gp, cumulativeGP, isSinglePlayer, (i % 2 == 0))
		end
	end

	-- ================================
	-- REGION 3: Anchored End GP Footer (only for single player)
	-- ================================
	if isSinglePlayer and #entries > 0 then
		local endGP = startingGP
		for _, entry in ipairs(entries) do
			endGP = endGP + importModule:CalculateGP(entry)
		end

		local footerGroup = AceGUI:Create("SimpleGroup")
		footerGroup:SetFullWidth(true)
		footerGroup:SetLayout("Fill")
		footerGroup:SetHeight(28)
		container:AddChild(footerGroup)

		local footerFrame = self:TrackContentFrame(CreateFrame("Frame", nil, footerGroup.frame, "BackdropTemplate"))
		footerFrame:SetAllPoints()
		footerFrame:SetBackdrop({
			bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
			edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
			edgeSize = 10,
			insets = { left = 3, right = 3, top = 3, bottom = 3 }
		})
		footerFrame:SetBackdropColor(0.08, 0.08, 0.12, 0.95)
		footerFrame:SetBackdropBorderColor(0.6, 0.5, 0, 1) -- Gold border

		local endGPLabel = footerFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
		endGPLabel:SetPoint("RIGHT", -12, 0)
		endGPLabel:SetText(string.format("|cffFFD700End GP:|r |cffffffff%s|r", Cerebro:FormatNumber(endGP)))
	end
end

-- Create a single loot history row
function UISandbox:CreateLootHistoryRow(container, entry, gp, cumulativeGP, showCumGP, isStripe)
	local ROW_HEIGHT = 28

	local wrapper = AceGUI:Create("SimpleGroup")
	wrapper:SetLayout("Fill")
	wrapper:SetFullWidth(true)
	wrapper:SetHeight(ROW_HEIGHT)
	container:AddChild(wrapper)

	local f = self:TrackContentFrame(CreateFrame("Frame", nil, wrapper.frame, "BackdropTemplate"))
	f:SetAllPoints()

	-- Stripe background
	if isStripe then
		local bg = f:CreateTexture(nil, "BACKGROUND")
		bg:SetAllPoints()
		bg:SetColorTexture(1, 1, 1, 0.04)
	end

	-- Player name (class-colored)
	local shortName = Cerebro:GetShortPlayerName(entry.player) or entry.player
	local classColor = "|cffFFFFFF"
	local playerData = Cerebro.db.global.players and Cerebro.db.global.players[entry.player]
	local playerClass = (playerData and playerData.class) or entry.class
	if playerClass then
		local cc = RAID_CLASS_COLORS and RAID_CLASS_COLORS[playerClass:upper()]
		if cc then classColor = "|c" .. cc.colorStr end
	end

	local nameFS = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
	nameFS:SetPoint("LEFT", 8, 0)
	nameFS:SetWidth(78)
	nameFS:SetText(classColor .. shortName .. "|r")
	nameFS:SetJustifyH("LEFT")
	nameFS:SetWordWrap(false)

	-- Time
	local timeFS = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
	timeFS:SetPoint("LEFT", 90, 0)
	timeFS:SetWidth(55)
	local timeStr = entry.time or ""
	if timeStr == "" and entry.servertime > 0 then
		timeStr = date("%H:%M", entry.servertime)
	end
	timeFS:SetText("|cff888888" .. timeStr .. "|r")
	timeFS:SetJustifyH("LEFT")

	-- Item name (truncated, colored by quality if we have the link)
	local itemFS = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
	itemFS:SetPoint("LEFT", 150, 0)
	itemFS:SetWidth(155)
	itemFS:SetJustifyH("LEFT")
	itemFS:SetWordWrap(false)

	local itemText = entry.itemName or entry.itemLink or "Unknown"
	if entry.itemLink and entry.itemLink:find("item:") then
		-- Try to color by rarity
		local _, _, rarity = C_Item.GetItemInfo(entry.itemLink)
		if rarity and ITEM_QUALITY_COLORS and ITEM_QUALITY_COLORS[rarity] then
			itemText = ITEM_QUALITY_COLORS[rarity].hex .. (entry.itemName or entry.itemLink) .. "|r"
		end
	end
	itemFS:SetText(itemText)

	-- Item tooltip on hover
	if entry.itemLink and entry.itemLink:find("item:") then
		f:EnableMouse(true)
		f:SetScript("OnEnter", function(self)
			GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
			GameTooltip:SetHyperlink(entry.itemLink)
			GameTooltip:Show()
		end)
		f:SetScript("OnLeave", function()
			GameTooltip:Hide()
		end)
	end

	-- Response
	local respFS = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
	respFS:SetPoint("LEFT", 310, 0)
	respFS:SetWidth(70)
	respFS:SetText("|cffaaaaaa" .. (entry.response or "?") .. "|r")
	respFS:SetJustifyH("LEFT")
	respFS:SetWordWrap(false)

	-- GP column
	local isGuildPlayer = Cerebro.db.global.players and Cerebro.db.global.players[entry.player]
	local gpText
	if not isGuildPlayer then
		gpText = "|cff666666N/A|r"
	elseif gp == 0 then
		gpText = "|cff4444440|r"
	else
		gpText = "|cffff8800" .. Cerebro:FormatNumber(gp) .. "|r"
	end

	local gpFS = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
	gpFS:SetPoint("RIGHT", -80, 0)
	gpFS:SetWidth(45)
	gpFS:SetText(gpText)
	gpFS:SetJustifyH("RIGHT")

	-- Cumulative GP column (only for single player)
	if showCumGP then
		local cumText
		if not isGuildPlayer then
			cumText = "|cff666666N/A|r"
		else
			cumText = "|cffffffff" .. Cerebro:FormatNumber(cumulativeGP) .. "|r"
		end

		local cumFS = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
		cumFS:SetPoint("RIGHT", -10, 0)
		cumFS:SetWidth(60)
		cumFS:SetText(cumText)
		cumFS:SetJustifyH("RIGHT")
	end
end
