-- BCUi_EvolvedRecipeUI.lua
-- Phase 1: Layout and dummy data only.
--
-- Provides a three column evolved recipe UI:
--  - Destinations (dishes)
--  - Main ingredients
--  - Seasoning
--
-- Inputs:
--  - playerObj: IsoPlayer
--  - baseItem: InventoryItem (dish container, e.g. Empty Roasting Pan)
--
-- Phase 1 does NOT touch real game data; it only renders a test UI.

require "ISUI/ISPanel"
require "ISUI/ISButton"
require "ISUI/ISLabel"
require "ISUI/ISScrollingListBox"

BC_EvolvedRecipeUI = ISPanel:derive("BC_EvolvedRecipeUI")

-------------------------------------------------
-- Constructor
-------------------------------------------------

function BC_EvolvedRecipeUI:new(x, y, width, height, playerObj, baseItem)
    local o = ISPanel:new(x or 0, y or 0, width or 900, height or 500)
    setmetatable(o, self)
    self.__index = self

    o.player = playerObj
    o.baseItem = baseItem

    o.borderColor = { r = 0.4, g = 0.4, b = 0.4, a = 1.0 }
    o.backgroundColor = { r = 0, g = 0, b = 0, a = 0.8 }
    o.moveWithMouse = true

    o.anchorBottom = true
    o.anchorRight = true

    o.selectedDestination = nil
    o.selectedIngredient = nil
    o.selectedSeasoning = nil

    o.projectedHunger = 0
    o.projectedBoredom = 0
    o.projectedHappiness = 0

    o.selectedIngredientName = ""
    o.selectedIngredientHunger = 0
    o.selectedSeasoningName = ""
    o.selectedSeasoningBoredom = 0
    o.selectedSeasoningHappiness = 0

    return o
end

-------------------------------------------------
-- Lifecycle
-------------------------------------------------

function BC_EvolvedRecipeUI:initialise()
    ISPanel.initialise(self)
end

function BC_EvolvedRecipeUI:createChildren()
    ISPanel.createChildren(self)

    local padding      = 10
    local headerHeight = 40
    local footerHeight = 50
    local listSpacing  = 10
    local bottomRowH   = 40  -- vertical space for Rename/Add buttons row

    -------------------------------------------------
    -- Header
    -------------------------------------------------
    local headerY = padding
    local headerX = padding
    local headerH = headerHeight

    self.headerLabel = ISLabel:new(
        headerX,
        headerY,
        headerH,
        self:getHeaderText(),
        1, 1, 1, 1,
        UIFont.Medium,
        true
    )
    self:addChild(self.headerLabel)

    -------------------------------------------------
    -- Content geometry
    -------------------------------------------------
    local contentY      = headerY + headerH + padding
    local contentTotalH = self.height - contentY - footerHeight - padding
    local listHeight    = contentTotalH - bottomRowH - 5

    -- 4 columns: [tooltip] [destinations] [ingredients] [seasoning]
    local columnWidth = math.floor((self.width - (padding * 2) - (listSpacing * 3)) / 4)

    local tooltipX = padding
    local destX    = tooltipX + columnWidth + listSpacing
    local midX     = destX    + columnWidth + listSpacing
    local rightX   = midX     + columnWidth + listSpacing

    -------------------------------------------------
    -- COLUMN 1: Embedded tooltip / info panel
    -- (For now still using simple "Nutritional Info"
    --  labels; later we’ll swap this to a real tooltip
    --  renderer + projected deltas.)
    -------------------------------------------------
    self.leftInfoPanel = ISPanel:new(
        tooltipX,
        contentY,
        columnWidth,
        contentTotalH
    )
    self.leftInfoPanel:initialise()
    self.leftInfoPanel:instantiate()
    self.leftInfoPanel.borderColor     = { r = 0.3, g = 0.3, b = 0.3, a = 1.0 }
    self.leftInfoPanel.backgroundColor = { r = 0.05, g = 0.05, b = 0.05, a = 0.9 }
    self.leftInfoPanel.anchorBottom    = true
    self:addChild(self.leftInfoPanel)

    local liPad = 6
    local lh    = getTextManager():getFontHeight(UIFont.Small) + 1
    local liY   = liPad

    self.nutritionTitle = ISLabel:new(
        liPad,
        liY,
        lh,
        "Nutritional Info:",
        1, 1, 1, 1,
        UIFont.Medium,
        true
    )
    self.leftInfoPanel:addChild(self.nutritionTitle)

    liY = liY + 4 + lh

    self.nutritionHungerLabel = ISLabel:new(
        liPad,
        liY,
        lh,
        "Hunger: 0",
        1, 1, 1, 1,
        UIFont.Small,
        true
    )
    self.leftInfoPanel:addChild(self.nutritionHungerLabel)

    liY = liY + lh

    self.nutritionBoredomLabel = ISLabel:new(
        liPad,
        liY,
        lh,
        "Boredom: 0",
        1, 1, 1, 1,
        UIFont.Small,
        true
    )
    self.leftInfoPanel:addChild(self.nutritionBoredomLabel)

    liY = liY + lh

    self.nutritionHappinessLabel = ISLabel:new(
        liPad,
        liY,
        lh,
        "Happiness: 0",
        1, 1, 1, 1,
        UIFont.Small,
        true
    )
    self.leftInfoPanel:addChild(self.nutritionHappinessLabel)

    -------------------------------------------------
    -- COLUMN 2: Destinations list
    -------------------------------------------------
    self.destinationsList = ISScrollingListBox:new(
        destX,
        contentY,
        columnWidth,
        listHeight
    )
    self.destinationsList:initialise()
    self.destinationsList:instantiate()
    self.destinationsList.itemheight   = 24
    self.destinationsList.font         = UIFont.Small
    self.destinationsList.drawBorder   = true

    -- Mouse handlers: (target, selectedItem.item)
    self.destinationsList.onmousedown        = BC_EvolvedRecipeUI.onDestinationMouseDown
    self.destinationsList.onRightMouseDown   = BC_EvolvedRecipeUI.onDestinationMouseDown
    self.destinationsList.onMouseDoubleClick = BC_EvolvedRecipeUI.onDestinationDoubleClick
    self.destinationsList.target             = self

    self.destinationsList.doDrawItem = BC_EvolvedRecipeUI.drawDestinationItem
    self:addChild(self.destinationsList)

    -------------------------------------------------
    -- COLUMN 3: Ingredients list
    -------------------------------------------------
    self.ingredientsList = ISScrollingListBox:new(
        midX,
        contentY,
        columnWidth,
        listHeight
    )
    self.ingredientsList:initialise()
    self.ingredientsList:instantiate()
    self.ingredientsList.itemheight   = 24
    self.ingredientsList.font         = UIFont.Small
    self.ingredientsList.drawBorder   = true

    self.ingredientsList.onmousedown        = BC_EvolvedRecipeUI.onIngredientMouseDown
    self.ingredientsList.onRightMouseDown   = BC_EvolvedRecipeUI.onIngredientMouseDown
    self.ingredientsList.onMouseDoubleClick = BC_EvolvedRecipeUI.onIngredientDoubleClick
    self.ingredientsList.target             = self

    self.ingredientsList.doDrawItem = BC_EvolvedRecipeUI.drawIngredientItem
    self:addChild(self.ingredientsList)

    -------------------------------------------------
    -- COLUMN 4: Seasoning list
    -------------------------------------------------
    self.seasoningList = ISScrollingListBox:new(
        rightX,
        contentY,
        columnWidth,
        listHeight
    )
    self.seasoningList:initialise()
    self.seasoningList:instantiate()
    self.seasoningList.itemheight   = 24
    self.seasoningList.font         = UIFont.Small
    self.seasoningList.drawBorder   = true

    self.seasoningList.onmousedown        = BC_EvolvedRecipeUI.onSeasoningMouseDown
    self.seasoningList.onRightMouseDown   = BC_EvolvedRecipeUI.onSeasoningMouseDown
    self.seasoningList.onMouseDoubleClick = BC_EvolvedRecipeUI.onSeasoningDoubleClick
    self.seasoningList.target             = self

    self.seasoningList.doDrawItem = BC_EvolvedRecipeUI.drawSeasoningItem
    self:addChild(self.seasoningList)

    -------------------------------------------------
    -- Bottom row: Rename / Add Ingredient / Add Seasoning
    -------------------------------------------------
    local bottomY = contentY + listHeight + 5
    local buttonW = 140
    local buttonH = 25

    -- Rename dish under destinations
    self.renameDishBtn = ISButton:new(
        destX + (columnWidth - buttonW) / 2,
        bottomY,
        buttonW,
        buttonH,
        "Rename Dish",
        self,
        BC_EvolvedRecipeUI.onRenameDishClicked
    )
    self.renameDishBtn:initialise()
    self.renameDishBtn:instantiate()
    self:addChild(self.renameDishBtn)

    -- Add ingredient under ingredients
    self.addIngredientBtn = ISButton:new(
        midX + (columnWidth - buttonW) / 2,
        bottomY,
        buttonW,
        buttonH,
        "Add Ingredient",
        self,
        BC_EvolvedRecipeUI.onAddIngredientClicked
    )
    self.addIngredientBtn:initialise()
    self.addIngredientBtn:instantiate()
    self:addChild(self.addIngredientBtn)

    -- Add seasoning under seasoning list
    self.addSeasoningBtn = ISButton:new(
        rightX + (columnWidth - buttonW) / 2,
        bottomY,
        buttonW,
        buttonH,
        "Add Seasoning",
        self,
        BC_EvolvedRecipeUI.onAddSeasoningClicked
    )
    self.addSeasoningBtn:initialise()
    self.addSeasoningBtn:instantiate()
    self:addChild(self.addSeasoningBtn)

    -------------------------------------------------
    -- Footer: Close button (bottom-right)
    -------------------------------------------------
    local footerY = self.height - footerHeight

    self.closeBtn = ISButton:new(
        self.width - padding - buttonW,
        footerY + (footerHeight - buttonH) / 2,
        buttonW,
        buttonH,
        getText("IGUI_CraftUI_Close") or "Close",
        self,
        BC_EvolvedRecipeUI.onCloseClicked
    )
    self.closeBtn:initialise()
    self.closeBtn:instantiate()
    self:addChild(self.closeBtn)
end

-------------------------------------------------
-- Data helpers
-------------------------------------------------

---Build a destination entry from the current baseItem.
---For now this is just the dish/container you right-clicked.
---@param item InventoryItem
---@return table
function BC_EvolvedRecipeUI:buildDestinationFromItem(item)
    if not item then
        return {
            name      = "Unknown Dish",
            hunger    = 0,
            boredom   = 0,
            happiness = 0,
            desc      = "No valid dish selected.",
            texture   = nil,
        }
    end

    local name = item:getDisplayName() or "Unknown Dish"
    local texture = item:getTex() or nil

    local hunger    = 0
    local boredom   = 0
    local happiness = 0

    -- If it's a Food, use its real stats.
    if instanceof(item, "Food") then
        hunger    = item:getHungerChange() or 0       -- usually negative
        boredom   = item:getBoredomChange() or 0
        happiness = item:getStressChange() or 0       -- in vanilla, "stressChange" is used for happiness mood effect
    end

    return {
        name      = name,
        hunger    = hunger,
        boredom   = boredom,
        happiness = happiness,
        desc      = "",       -- We can fill this from script data later.
        texture   = texture,
    }
end

-------------------------------------------------
-- Temporary data: real destination, dummy ingredients/seasoning
-------------------------------------------------

function BC_EvolvedRecipeUI:populateDummyData()
    self.destinationsList:clear()
    self.ingredientsList:clear()
    self.seasoningList:clear()

    -------------------------------------------------
    -- DESTINATION: real baseItem you right-clicked
    -------------------------------------------------
    local destData = self:buildDestinationFromItem(self.baseItem)
    self.destinationsList:addItem(destData.name, { text = destData.name, item = destData })

    if #self.destinationsList.items > 0 then
        self.destinationsList.selected = 1
        self.selectedDestination = self.destinationsList.items[1].item.item
        self:updateNutritionFromDestination()
    else
        self.selectedDestination = nil
        self:updateNutritionFromDestination()
    end

    -------------------------------------------------
    -- INGREDIENTS + SEASONING: still dummy for now
    -- (These will be replaced by real evolved recipe
    --  lookups in the next Phase 2 steps.)
    -------------------------------------------------

    local ing = {
        { name = "Raw Meat Chunks", hunger = -20, amountUsed = "50%", amountLeft = "50%", desc = "Adds protein and satiety.", texture = nil },
        { name = "Potato",          hunger = -10, amountUsed = "100%", amountLeft = "0%",  desc = "Starchy vegetable, good filler.", texture = nil },
        { name = "Carrot",          hunger = -5,  amountUsed = "100%", amountLeft = "0%",  desc = "Adds a little nutrition and crunch.", texture = nil },
    }

    for _, i in ipairs(ing) do
        self.ingredientsList:addItem(i.name, { text = i.name, item = i })
    end

    local seasoning = {
        { name = "Salt",   hunger = 0, boredom = 0, happiness = 0, desc = "Improves taste slightly.", texture = nil },
        { name = "Pepper", hunger = 0, boredom = 0, happiness = 0, desc = "Adds a bit of heat and flavor.", texture = nil },
        { name = "Herbs",  hunger = 0, boredom = 0, happiness = 0, desc = "Mixed herbs for aroma.", texture = nil },
    }

    for _, s in ipairs(seasoning) do
        self.seasoningList:addItem(s.name, { text = s.name, item = s })
    end
end

-------------------------------------------------
-- Helpers
-------------------------------------------------

function BC_EvolvedRecipeUI:getHeaderText()
    local baseName = self.baseItem and self.baseItem:getDisplayName() or "Unknown Dish"
    return "BCUi - Evolved Recipe: " .. baseName
end

function BC_EvolvedRecipeUI:updateNutritionFromDestination()
    local dest = self.selectedDestination
    if dest then
        self.projectedHunger    = dest.hunger    or 0
        self.projectedBoredom   = dest.boredom   or 0
        self.projectedHappiness = dest.happiness or 0
    else
        self.projectedHunger    = 0
        self.projectedBoredom   = 0
        self.projectedHappiness = 0
    end

    -- Update the embedded tooltip-style summary
    if self.tooltipHungerLabel then
        self.tooltipHungerLabel.name = string.format("Hunger: %d", self.projectedHunger)
    end
    if self.tooltipBoredomLabel then
        self.tooltipBoredomLabel.name = string.format("Boredom: %d", self.projectedBoredom)
    end
    if self.tooltipHappinessLabel then
        self.tooltipHappinessLabel.name = string.format("Happiness: %d", self.projectedHappiness)
    end

    -- Reset projection strip when the base dish changes / clears
    if self.projIngredientLabel then
        self.projIngredientLabel.name = "Ingredient adds: --"
    end
    if self.projSeasoningLabel then
        self.projSeasoningLabel.name = "Seasoning adds: --"
    end
end

function BC_EvolvedRecipeUI:updateNutritionFromIngredient()
    local destHunger = (self.selectedDestination and self.selectedDestination.hunger) or 0
    local ingHunger  = (self.selectedIngredient   and self.selectedIngredient.hunger) or 0

    local deltaHunger = ingHunger  -- for now, ingredient just adds its hunger directly

    if self.projIngredientLabel then
        if self.selectedIngredient then
            self.projIngredientLabel.name = string.format(
                "Ingredient adds: %+d Hunger",
                deltaHunger
            )
        else
            self.projIngredientLabel.name = "Ingredient adds: --"
        end
    end
end

function BC_EvolvedRecipeUI:updateFromSeasoning()
    self.selectedSeasoningName = self.selectedSeasoning and self.selectedSeasoning.name or ""

    local boredom   = self.selectedSeasoning and (self.selectedSeasoning.boredom   or 0) or 0
    local happiness = self.selectedSeasoning and (self.selectedSeasoning.happiness or 0) or 0

    if self.projSeasoningLabel then
        if self.selectedSeasoning then
            self.projSeasoningLabel.name = string.format(
                "Seasoning adds: %+d Happiness, %+d Boredom",
                happiness,
                boredom
            )
        else
            self.projSeasoningLabel.name = "Seasoning adds: --"
        end
    end
end

-------------------------------------------------
-- Row drawing (with icon hook)
-------------------------------------------------

local function drawRowWithIcon(list, y, item, text, isSelected)
    local a = 0.9
    local r, g, b = 1, 1, 1
    if isSelected then
        r, g, b = 0.9, 0.9, 0.3
    end

    local tex = item.item.item.texture
    local iconX = 4
    local textX = 4

    if tex then
        list:drawTextureScaledAspect(tex, iconX, y + 2, 20, 20, 1, 1, 1, a)
        textX = 28
    end

    list:drawText(text, textX, y + 4, r, g, b, a, list.font)
    return y + list.itemheight
end

function BC_EvolvedRecipeUI:drawDestinationItem(y, item, alt)
    local list = self
    local text = item.text
    local isSelected = (list.selected == item.index)
    return drawRowWithIcon(list, y, item, text, isSelected)
end

function BC_EvolvedRecipeUI:drawIngredientItem(y, item, alt)
    local list = self
    local data = item.item.item
    local hunger = data.hunger or 0
    local text = string.format("%s  (hunger %d)", item.text, hunger)
    local isSelected = (list.selected == item.index)
    return drawRowWithIcon(list, y, item, text, isSelected)
end

function BC_EvolvedRecipeUI:drawSeasoningItem(y, item, alt)
    local list = self
    local text = item.text
    local isSelected = (list.selected == item.index)
    return drawRowWithIcon(list, y, item, text, isSelected)
end

-------------------------------------------------
-- List mouse handlers
-------------------------------------------------

-- Called as onDestinationMouseDown(self, item)
function BC_EvolvedRecipeUI:onDestinationMouseDown(item)
    if not item then return end

    -- Our addItem call used: addItem(text, { text = name, item = data })
    -- so `item` here is that table, and `item.item` is the data payload.
    self.selectedDestination = item.item
    self.selectedIngredient  = nil
    self.selectedSeasoning   = nil

    -- Clear selections in the other lists
    self.ingredientsList.selected = -1
    self.seasoningList.selected   = -1

    -- Reset selected-name caches
    self.selectedIngredientName   = ""
    self.selectedIngredientHunger = 0
    self.selectedSeasoningName    = ""

    -- Reset labels under Ingredients/Seasonings panels
    if self.selectedIngredientLabel then
        self.selectedIngredientLabel.name = "[Selected Ingredient]:"
    end
    if self.selectedIngredientHungerLabel then
        self.selectedIngredientHungerLabel.name = "Hunger: 0"
    end
    if self.selectedSeasoningLabel then
        self.selectedSeasoningLabel.name = "[Selected Seasoning]:"
    end
    if self.selectedSeasoningBoredomLabel then
        self.selectedSeasoningBoredomLabel.name = "Boredom: 0"
    end
    if self.selectedSeasoningHappinessLabel then
        self.selectedSeasoningHappinessLabel.name = "Happiness: 0"
    end

    -- Refresh the nutrition panel for the new base dish
    self:updateNutritionFromDestination()
end

function BC_EvolvedRecipeUI:onDestinationDoubleClick(item)
    -- Phase 1: no-op (later: "open/add ingredient" maybe)
end

-- Called as onIngredientMouseDown(self, item)
function BC_EvolvedRecipeUI:onIngredientMouseDown(item)
    if not item then return end

    self.selectedIngredient       = item.item

    self.selectedIngredientName   = self.selectedIngredient.name    or ""
    self.selectedIngredientHunger = self.selectedIngredient.hunger  or 0

    if self.selectedIngredientLabel then
        self.selectedIngredientLabel.name =
            string.format("[Selected Ingredient]: %s", self.selectedIngredientName)
    end

    if self.selectedIngredientHungerLabel then
        self.selectedIngredientHungerLabel.name =
            string.format("Hunger: %d", self.selectedIngredientHunger)
    end

    self:updateNutritionFromIngredient()
end

function BC_EvolvedRecipeUI:onIngredientDoubleClick(item)
    -- Phase 1: no-op (later: perform the actual Add Ingredient action)
end

-- Called as onSeasoningMouseDown(self, item)
function BC_EvolvedRecipeUI:onSeasoningMouseDown(item)
    if not item then return end

    self.selectedSeasoning       = item.item

    self.selectedSeasoningName   = self.selectedSeasoning.name      or ""
    local boredom   = self.selectedSeasoning.boredom   or 0
    local happiness = self.selectedSeasoning.happiness or 0

    if self.selectedSeasoningLabel then
        self.selectedSeasoningLabel.name =
            string.format("[Selected Seasoning]: %s", self.selectedSeasoningName)
    end

    if self.selectedSeasoningBoredomLabel then
        self.selectedSeasoningBoredomLabel.name =
            string.format("Boredom: %d", boredom)
    end

    if self.selectedSeasoningHappinessLabel then
        self.selectedSeasoningHappinessLabel.name =
            string.format("Happiness: %d", happiness)
    end

    self:updateFromSeasoning()
end

function BC_EvolvedRecipeUI:onSeasoningDoubleClick(item)
    -- Phase 1: no-op (later: perform the actual Add Seasoning action)
end

-------------------------------------------------
-- Buttons
-------------------------------------------------

function BC_EvolvedRecipeUI:onRenameDishClicked()
    -- Phase 1: placeholder; will open a rename text box in a later step.
end

function BC_EvolvedRecipeUI:onAddIngredientClicked()
    self.selectedIngredient = nil
    self.ingredientsList.selected = -1
    self.selectedIngredientName = ""
    self.selectedIngredientHunger = 0

    -- Reset nutrition to base destination when ingredient selection is cleared
    self:updateNutritionFromDestination()
end

function BC_EvolvedRecipeUI:onAddSeasoningClicked()
    self.selectedSeasoning = nil
    self.seasoningList.selected = -1
    self.selectedSeasoningName = ""

    -- Reset nutrition to base destination when seasoning selection is cleared
    self:updateNutritionFromDestination()
end

function BC_EvolvedRecipeUI:onCloseClicked()
    self:close()
end

-------------------------------------------------
-- Close / open helpers
-------------------------------------------------

function BC_EvolvedRecipeUI:close()
    self:setVisible(false)
    self:removeFromUIManager()
end

function BC_EvolvedRecipeUI.openFor(playerObj, baseItem)
    local uiW, uiH = 900, 500
    local x = (getCore():getScreenWidth() - uiW) / 2
    local y = (getCore():getScreenHeight() - uiH) / 2

    local ui = BC_EvolvedRecipeUI:new(x, y, uiW, uiH, playerObj, baseItem)
    ui:initialise()
    ui:instantiate()
    ui:addToUIManager()
    ui:setVisible(true)
    ui:bringToTop()
    return ui
end

-- local player = getSpecificPlayer(0)
-- local inv = player:getInventory()
-- local baseItem = inv:getFirstType("RoastingPan") or inv:getFirstType("Pan") or inv:getItems():get(0)
-- BCUi_EvolvedRecipeUI.openFor(player, baseItem)