local addonName, addon = ...
local UI = addon.UI

local REPEAT_TEXT = {
    none = "NONE",
    day = "EVERY DAY",
    week = "EVERY WEEK",
    month = "EVERY MONTH",
    custom = "CUSTOM",
}

function UI:GetTaskEditorData()
    local title = strtrim(self.TaskInput:GetText() or "")
    if title == "" then return nil end

    local dueDate = nil
    if self.NewTaskHasDate and self.SelectedDate then
        dueDate = {
            year = self.SelectedDate.year,
            month = self.SelectedDate.month,
            day = self.SelectedDate.day,
        }
    end

    local hasTime = self.NewTaskHasTime and dueDate ~= nil
    local hour = math.max(0, math.min(23, tonumber(self.HourInput:GetText()) or 0))
    local minute = math.max(0, math.min(59, tonumber(self.MinuteInput:GetText()) or 0))

    local repeatType, repeatInterval, repeatUnit =
        addon.DB:NormalizeRepeat(
            self.RepeatType,
            tonumber(self.IntervalInput:GetText()) or 1,
            self.RepeatUnit
        )

    return {
        title = title,
        dueDate = dueDate,
        hasTime = hasTime,
        dueTime = hasTime and { hour = hour, minute = minute } or nil,
        repeatType = repeatType,
        repeatInterval = repeatInterval,
        repeatUnit = repeatUnit,
        category = self.NewTaskCategory or addon.DB.CATEGORIES.OTHER,
        characterKey = self.NewTaskCharacterKey,
        specID = self.NewTaskSpecID,
        specName = self.NewTaskSpecName,
        professionID = self.NewTaskProfessionID,
        professionName = self.NewTaskProfessionName,
        instanceID = self.NewTaskInstanceID,
        instanceName = self.NewTaskInstanceName,
        dungeonMode = self.NewTaskCategory == "DUNGEON" and "KEYS" or nil,
        raidExpansionName = self.NewTaskCategory == "RAID"
            and self.NewTaskRaidExpansion or nil,
    }
end

function UI:ResetEditorVisualState()
    self.EditingTaskID = nil
    self.AddButton:SetText(self:T("CREATE", "ADD"))
    self.CancelEditButton:Hide()
    self.TaskInput:SetText("")
    self.RepeatType = "none"
    self.RepeatInterval = 1
    self.RepeatUnit = "days"
    UIDropDownMenu_SetText(self.RepeatDropDown, self:T("NONE", "NONE"))
    self.CustomRepeatPanel:Hide()
    self.NewTaskHasTime = false
    self.TimeCheck:SetChecked(false)
    if self.UpdateTimeControls then self.UpdateTimeControls() end
end

function UI:CancelTaskEdit()
    self:ResetEditorVisualState()
    self.NewTaskCategory = addon.DB.CATEGORIES.OTHER
    UIDropDownMenu_SetText(self.CategoryDropDown, self:T("OTHER", "OTHER"))
    if self.ResetNewTaskContext then self:ResetNewTaskContext() end
    if self.RefreshTaskContextSelectors then self:RefreshTaskContextSelectors() end
end

function UI:BeginEditTask(taskID)
    local task = addon.DB:FindTask(taskID)
    if not task then return end

    self.EditingTaskID = task.id
    self.TaskInput:SetText(task.title or "")

    if task.dueDate then
        self.NewTaskHasDate = true
        self.SelectedDate = {
            year = task.dueDate.year,
            month = task.dueDate.month,
            day = task.dueDate.day,
        }
        self.DateButton:SetText(self:FormatDate(self.SelectedDate))
    else
        self.NewTaskHasDate = false
        self.DateButton:SetText(self:T("NO_DATE", "NO DATE"))
    end

    self.NewTaskHasTime = addon.DB:TaskHasTime(task)
    self.TimeCheck:SetChecked(self.NewTaskHasTime)
    if task.dueTime then
        self.HourInput:SetText(string.format("%02d", tonumber(task.dueTime.hour) or 0))
        self.MinuteInput:SetText(string.format("%02d", tonumber(task.dueTime.minute) or 0))
    end
    if self.UpdateTimeControls then self.UpdateTimeControls() end

    self.RepeatType = task.repeatType or "none"
    self.RepeatInterval = task.repeatInterval or 1
    self.RepeatUnit = task.repeatUnit or "days"
    self.IntervalInput:SetText(tostring(self.RepeatInterval))
    UIDropDownMenu_SetText(self.RepeatDropDown, self:LT(REPEAT_TEXT[self.RepeatType] or "NONE"))
    UIDropDownMenu_SetText(self.UnitDropDown, self:LT(string.upper(self.RepeatUnit)))
    if self.RepeatType == "custom" then
        self.CustomRepeatPanel:Show()
    else
        self.CustomRepeatPanel:Hide()
    end

    self.NewTaskCategory = task.category or addon.DB.CATEGORIES.OTHER
    UIDropDownMenu_SetText(
        self.CategoryDropDown,
        self:LT(addon.DB:GetCategoryLabel(self.NewTaskCategory))
    )

    if self.ResetNewTaskContext then self:ResetNewTaskContext() end
    self.NewTaskCharacterKey = task.characterKey
    self.NewTaskSpecID = task.specID
    self.NewTaskSpecName = task.specName
    self.NewTaskProfessionID = task.professionID
    self.NewTaskProfessionName = task.professionName
    self.NewTaskInstanceID = task.instanceID
    self.NewTaskInstanceName = task.instanceName
    self.NewTaskDungeonMode = task.dungeonMode
    self.NewTaskRaidExpansion = task.raidExpansionName

    if self.RefreshTaskContextSelectors then self:RefreshTaskContextSelectors() end

    self.AddButton:SetText(UI:LT("SAVE"))
    self.CancelEditButton:Show()
    self.TaskInput:SetFocus()
end

function UI:CloseEditSeriesPopup()
    if self.EditSeriesPopup then
        self.EditSeriesPopup:Hide()
        self.EditSeriesPopup:SetParent(nil)
        self.EditSeriesPopup = nil
    end
end

function UI:FinishTaskEdit()
    self:CloseEditSeriesPopup()
    self:ResetEditorVisualState()
    self:Refresh()
end

function UI:ApplyTaskEdit(applySeries)
    local id = self.EditingTaskID
    if not id then return end

    local data = self:GetTaskEditorData()
    if not data then return end

    if applySeries then
        addon.DB:UpdateTaskSeries(id, data)
    else
        addon.DB:UpdateTask(id, data)
    end

    self:FinishTaskEdit()
end

function UI:ShowEditSeriesPopup()
    self:CloseEditSeriesPopup()

    local popup = CreateFrame("Frame", nil, self.MainFrame, "BackdropTemplate")
    self.EditSeriesPopup = popup
    popup:SetSize(330, 130)
    popup:SetPoint("CENTER", self.MainFrame, "CENTER")
    popup:SetFrameStrata("TOOLTIP")
    popup:EnableMouse(true)
    popup:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8X8",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        edgeSize = 12,
    })
    popup:SetBackdropColor(unpack(self.COLORS.panel))
    popup:SetBackdropBorderColor(unpack(self.COLORS.border))

    local text = popup:CreateFontString(nil, "OVERLAY")
    text:SetFontObject(GameFontNormal)
    text:SetPoint("TOPLEFT", popup, "TOPLEFT", 12, -16)
    text:SetPoint("TOPRIGHT", popup, "TOPRIGHT", -12, -16)
    text:SetJustifyH("CENTER")
    text:SetText(UI:LT("SAVE CHANGES TO REPEATING TASK?"))

    local thisOne = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    thisOne:SetSize(92, 28)
    thisOne:SetPoint("BOTTOMLEFT", popup, "BOTTOMLEFT", 12, 14)
    thisOne:SetText(self:T("THIS_ONE", "THIS ONE"))
    thisOne:SetScript("OnClick", function() self:ApplyTaskEdit(false) end)

    local all = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    all:SetSize(92, 28)
    all:SetPoint("LEFT", thisOne, "RIGHT", 10, 0)
    all:SetText(self:T("ALL", "ALL"))
    all:SetScript("OnClick", function() self:ApplyTaskEdit(true) end)

    local cancel = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    cancel:SetSize(92, 28)
    cancel:SetPoint("LEFT", all, "RIGHT", 10, 0)
    cancel:SetText(self:T("CANCEL", "CANCEL"))
    cancel:SetScript("OnClick", function() self:CloseEditSeriesPopup() end)
end

function UI:SaveTaskEdits()
    local task = addon.DB:FindTask(self.EditingTaskID)
    if not task then
        self:CancelTaskEdit()
        return
    end

    if task.seriesID and task.repeatType ~= "none" then
        self:ShowEditSeriesPopup()
    else
        self:ApplyTaskEdit(false)
    end
end
