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

    @module UI.Tabs.History
    @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: History (Transaction Log)
===============================================]]

-- Search text storage for history tab
UISandbox.historySearchText = ""

function UISandbox:DrawHistoryTab(container)
	local transactions = Cerebro.db.global.transactions or {}

	-- Header
	local header = AceGUI:Create("Heading")
	header:SetText("Transaction History")
	header:SetFullWidth(true)
	container:AddChild(header)

	-- Search bar
	local searchGroup = AceGUI:Create("SimpleGroup")
	searchGroup:SetFullWidth(true)
	searchGroup:SetLayout("Flow")
	container:AddChild(searchGroup)

	local searchBox = AceGUI:Create("EditBox")
	searchBox:SetLabel("")
	searchBox:SetWidth(250)
	searchBox:SetText(self.historySearchText or "")
	searchBox:DisableButton(true)
	searchGroup:AddChild(searchBox)

	local searchBtn = AceGUI:Create("Button")
	searchBtn:SetText("Search")
	searchBtn:SetWidth(80)
	searchBtn:SetCallback("OnClick", function()
		self.historySearchText = searchBox:GetText()
		self:SelectTab("history")
	end)
	searchGroup:AddChild(searchBtn)

	local clearBtn = AceGUI:Create("Button")
	clearBtn:SetText("Clear")
	clearBtn:SetWidth(60)
	clearBtn:SetCallback("OnClick", function()
		self.historySearchText = ""
		searchBox:SetText("")
		self:SelectTab("history")
	end)
	searchGroup:AddChild(clearBtn)

	-- Count display
	local countLabel = AceGUI:Create("Label")
	countLabel:SetWidth(120)
	searchGroup:AddChild(countLabel)

	-- Empty state
	if #transactions == 0 then
		local spacer = AceGUI:Create("Label")
		spacer:SetText("\n\n")
		spacer:SetFullWidth(true)
		container:AddChild(spacer)

		local emptyLabel = AceGUI:Create("Label")
		emptyLabel:SetText("|cff666666No transactions recorded yet.\n\nEP/GP changes will appear here.|r")
		emptyLabel:SetFullWidth(true)
		container:AddChild(emptyLabel)
		return
	end

	-- Filter transactions
	local searchFilter = (self.historySearchText or ""):lower()
	local filtered = {}

	-- Process in reverse order (newest first)
	for i = #transactions, 1, -1 do
		local tx = transactions[i]

		-- Build searchable text
		local playerName = tx.player or "Unknown"
		local reason = tx.reason or "Unknown"
		local currency = tx.currency or tx.type or "?"
		local admin = tx.admin or "System"
		local details = ""
		if type(tx.details) == "string" then
			details = tx.details
		elseif type(tx.details) == "table" then
			if tx.details.item then details = tx.details.item end
			if tx.details.reason then details = tx.details.reason end
		end

		local searchText = string.format("%s %s %s %s %s",
			playerName, reason, currency, admin, details):lower()

		if not tx.voided and (searchFilter == "" or searchText:find(searchFilter, 1, true)) then
			table.insert(filtered, tx)
			if #filtered >= 100 then break end
		end
	end

	-- Update count
	countLabel:SetText(string.format("|cff888888%d of %d|r", #filtered, #transactions))

	-- Scrollable content
	local scroll = AceGUI:Create("ScrollFrame")
	scroll:SetLayout("Flow")
	scroll:SetFullWidth(true)
	scroll:SetFullHeight(true)
	container:AddChild(scroll)

	-- Header row
	self:CreateHistoryRow(scroll, nil, true, false)

	-- Transaction rows
	for i, tx in ipairs(filtered) do
		self:CreateHistoryRow(scroll, tx, false, (i % 2 == 0))
	end

	if #filtered == 0 and searchFilter ~= "" then
		local noMatch = AceGUI:Create("Label")
		noMatch:SetText("\n|cff666666No transactions match your search.|r")
		noMatch:SetFullWidth(true)
		scroll:AddChild(noMatch)
	end
end

function UISandbox:CreateHistoryRow(container, tx, isHeader, isStripe)
	local ROW_HEIGHT = 28

	-- AceGUI wrapper
	local wrapper = AceGUI:Create("SimpleGroup")
	wrapper:SetLayout("Fill")
	wrapper:SetFullWidth(true)
	wrapper:SetHeight(isHeader and 22 or ROW_HEIGHT)
	container:AddChild(wrapper)

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

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

	if isHeader then
		-- Header labels
		local fsDate = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
		fsDate:SetPoint("LEFT", 5, 0)
		fsDate:SetText("|cffFFD700Date|r")

		local fsPlayer = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
		fsPlayer:SetPoint("LEFT", 70, 0)
		fsPlayer:SetText("|cffFFD700Player|r")

		local fsAmount = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
		fsAmount:SetPoint("LEFT", 175, 0)
		fsAmount:SetText("|cffFFD700Change|r")

		local fsReason = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
		fsReason:SetPoint("LEFT", 260, 0)
		fsReason:SetText("|cffFFD700Reason|r")

		local fsAdmin = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
		fsAdmin:SetPoint("RIGHT", -5, 0)
		fsAdmin:SetText("|cffFFD700By|r")
		return
	end

	-- == DATA ROW ==

	-- Date/Time
	local dateFS = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	dateFS:SetPoint("LEFT", 5, 0)
	dateFS:SetWidth(60)
	dateFS:SetText("|cff888888" .. date("%m/%d %H:%M", tx.timestamp or 0) .. "|r")
	dateFS:SetJustifyH("LEFT")

	-- Player name with class color
	local playerName = tx.player or "Unknown"
	local shortName = Cerebro:GetShortPlayerName(playerName)
	local playerData = Cerebro.db.global.players and Cerebro.db.global.players[playerName]
	local classColor = "|cffFFFFFF"
	if playerData and playerData.class then
		local cc = RAID_CLASS_COLORS and RAID_CLASS_COLORS[playerData.class]
		if cc then classColor = "|c" .. cc.colorStr end
	end

	local playerFS = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	playerFS:SetPoint("LEFT", 70, 0)
	playerFS:SetWidth(100)
	playerFS:SetText(classColor .. shortName .. "|r")
	playerFS:SetJustifyH("LEFT")
	playerFS:SetWordWrap(false)

	-- Amount with color (green for EP+, red for GP+/EP-)
	local amount = tx.amount or 0
	local currency = tx.currency or tx.type or "?"
	local amountColor = "|cff00ff00"  -- Default green
	local sign = "+"

	if amount < 0 then
		amountColor = "|cffff4444"  -- Red for negative
		sign = ""
	elseif currency == "GP" then
		amountColor = "|cffff8800"  -- Orange for GP charges
	end

	local amountFS = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	amountFS:SetPoint("LEFT", 175, 0)
	amountFS:SetWidth(75)
	amountFS:SetText(string.format("%s%s%d %s|r", amountColor, sign, amount, currency))
	amountFS:SetJustifyH("LEFT")

	-- Reason
	local reason = tx.reason or "Unknown"
	local reasonFS = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	reasonFS:SetPoint("LEFT", 260, 0)
	reasonFS:SetWidth(130)
	reasonFS:SetText(reason)
	reasonFS:SetJustifyH("LEFT")
	reasonFS:SetWordWrap(false)

	-- Admin (right-aligned)
	local admin = Cerebro:GetShortPlayerName(tx.admin or "System")
	local adminFS = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	adminFS:SetPoint("RIGHT", -5, 0)
	adminFS:SetWidth(80)
	adminFS:SetText("|cff00ccff" .. admin .. "|r")
	adminFS:SetJustifyH("RIGHT")
	adminFS:SetWordWrap(false)

	-- Tooltip on hover with full details
	f:EnableMouse(true)
	f:SetScript("OnEnter", function(self)
		GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
		GameTooltip:AddLine("Transaction Details", 1, 0.82, 0)
		GameTooltip:AddLine(" ")
		GameTooltip:AddDoubleLine("Player:", playerName, 1, 1, 1, 0.7, 0.7, 0.7)
		GameTooltip:AddDoubleLine("Amount:", string.format("%s%d %s", sign, amount, currency), 1, 1, 1, 0.7, 0.7, 0.7)
		GameTooltip:AddDoubleLine("Reason:", reason, 1, 1, 1, 0.7, 0.7, 0.7)
		GameTooltip:AddDoubleLine("By:", tx.admin or "System", 1, 1, 1, 0, 0.8, 1)
		GameTooltip:AddDoubleLine("Date:", date("%Y-%m-%d %H:%M:%S", tx.timestamp or 0), 1, 1, 1, 0.5, 0.5, 0.5)

		-- Session info if present
		if tx.sessionName then
			GameTooltip:AddLine(" ")
			GameTooltip:AddDoubleLine("Session:", tx.sessionName, 1, 1, 1, 0.7, 0.7, 0.7)
		end

		-- Details if present
		if type(tx.details) == "table" then
			GameTooltip:AddLine(" ")
			if tx.details.item then
				GameTooltip:AddLine("Item: " .. tx.details.item, 1, 1, 1)
			end
			if tx.details.preGP and tx.details.postGP then
				GameTooltip:AddDoubleLine("GP Change:",
					string.format("%d → %d", tx.details.preGP, tx.details.postGP),
					1, 1, 1, 1, 0.5, 0)
			end
			if tx.details.mapID then
				GameTooltip:AddDoubleLine("M+ Level:", tx.details.level or "?", 1, 1, 1, 0.7, 0.7, 0.7)
			end
		elseif type(tx.details) == "string" and tx.details ~= "" then
			GameTooltip:AddLine(" ")
			GameTooltip:AddLine("Details: " .. tx.details, 0.7, 0.7, 0.7, true)
		end

		-- Legacy marker
		if not tx.logicVersion then
			GameTooltip:AddLine(" ")
			GameTooltip:AddLine("|cffff8800* Legacy transaction|r", 1, 0.5, 0)
		end

		GameTooltip:Show()
	end)
	f:SetScript("OnLeave", function()
		GameTooltip:Hide()
	end)
end
