local fontPath = "Interface/AddOns/WoWStudy/Fonts/NotoSansCJK-Medium.ttc"

function WoWStudyFunction.SetupFlashcardCreationPanel(menuFrame, menuPanel2)
    local flashcardCreationPanel = CreateFrame("Frame", "WoWStudyFlashcardCreationPanel", menuFrame, "ShadowOverlayTemplate")
    flashcardCreationPanel:SetPoint("LEFT", menuPanel2, "RIGHT", 10, 0)
    flashcardCreationPanel:SetSize(600, 489)
    flashcardCreationPanel:Hide()

    local title = flashcardCreationPanel:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOP", flashcardCreationPanel, "TOP", 0, -10)
    title:SetText("Create Flashcards")

    -----------------------------------------------------------------------
    -- Main Container for input
    -----------------------------------------------------------------------
    local scrollFrame = CreateFrame("ScrollFrame", nil, flashcardCreationPanel, "UIPanelScrollFrameTemplate")
    scrollFrame:SetPoint("TOPLEFT", flashcardCreationPanel, "TOPLEFT", 0, -40)
    scrollFrame:SetPoint("BOTTOMRIGHT", flashcardCreationPanel, "BOTTOMRIGHT", -30, 10)
    -- UIPanelScrollFrameTemplate includes a scrollbar and up/down arrows. 
    -- If you prefer raw mouse-wheel only, remove the template 
    -- and handle OnMouseWheel manually.

    local scrollChild = CreateFrame("Frame", nil, scrollFrame)
    scrollChild:SetSize(1,1)  -- Will be expanded based on content
    scrollFrame:SetScrollChild(scrollChild)

    -- A convenience width for all elements inside the scrollchild
    local PANEL_WIDTH = 550

    -----------------------------------------------------------------------
    -- Add Deck
    -----------------------------------------------------------------------
    local deckTitle = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    deckTitle:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", 10, -10)
    deckTitle:SetText("Add a Deck:")
    deckTitle:SetFont(fontPath, 12)

    local deckNameLabel = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    deckNameLabel:SetPoint("TOPLEFT", deckTitle, "BOTTOMLEFT", 0, -20)
    deckNameLabel:SetText("Deck Name:")

    local deckNameEditBox = CreateFrame("EditBox", nil, scrollChild, "InputBoxTemplate")
    deckNameEditBox:SetSize(200, 30)
    deckNameEditBox:SetPoint("LEFT", deckNameLabel, "RIGHT", 10, 0)
    deckNameEditBox:SetAutoFocus(false)
    deckNameEditBox:SetMultiLine(false) -- keep single line for deck name
    deckNameEditBox:SetFont(fontPath, 12, "OUTLINE")

    local createDeckButton = CreateFrame("Button", nil, scrollChild, "UIPanelButtonTemplate")
    createDeckButton:SetSize(140, 30)
    createDeckButton:SetPoint("LEFT", deckNameEditBox, "RIGHT", 10, 0)
    createDeckButton:SetText("Create Deck")

    -----------------------------------------------------------------------
    -- Add Card
    -----------------------------------------------------------------------
    local cardTitle = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    cardTitle:SetPoint("TOPLEFT", deckNameLabel, "BOTTOMLEFT", 0, -35)
    cardTitle:SetText("Add a Card:")
    cardTitle:SetFont(fontPath, 12)

    local deckDropdownLabel = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    deckDropdownLabel:SetPoint("TOPLEFT", cardTitle, "BOTTOMLEFT", 0, -20)
    deckDropdownLabel:SetText("Deck:")
    deckDropdownLabel:SetFont(fontPath, 12)

    local deckDropdown = CreateFrame("Frame", "WoWStudy_CardDeckDropdown", scrollChild, "UIDropDownMenuTemplate")
    deckDropdown:SetPoint("LEFT", deckDropdownLabel, "RIGHT", 0, -2)
    UIDropDownMenu_SetWidth(deckDropdown, 140)
    UIDropDownMenu_SetText(deckDropdown, "Select Deck")

    local selectedDeck = nil

    local function UpdateDeckDropdown()
        local loadedDecks = {}

        if WoWStudySaved.decks then
            for deckName, deck in pairs(WoWStudySaved.decks or {}) do
                if deck.source == "internal" then
                    table.insert(loadedDecks, deckName)
                end
            end
        end
    
        table.sort(loadedDecks)

        local function OnClick(self)
            selectedDeck = self.value
            UIDropDownMenu_SetSelectedValue(deckDropdown, self.value)
        end

        UIDropDownMenu_Initialize(deckDropdown, function(self, level)
            for _, deckName in ipairs(loadedDecks) do
                local info = UIDropDownMenu_CreateInfo()
                info.text = deckName
                info.value = deckName
                info.func = OnClick
                UIDropDownMenu_AddButton(info, level)
            end
        end)

        if #loadedDecks > 0 then
            UIDropDownMenu_SetSelectedValue(deckDropdown, loadedDecks[1])
            selectedDeck = loadedDecks[1]
        else
            UIDropDownMenu_SetText(deckDropdown, "No decks")
            selectedDeck = nil
        end
    end

    local cardTypeLabel = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    cardTypeLabel:SetPoint("TOPLEFT", deckDropdownLabel, "BOTTOMLEFT", 0, -40)
    cardTypeLabel:SetText("Card Type:")

    local cardType = "hidden"

    local hiddenRadio = CreateFrame("CheckButton", nil, scrollChild, "UIRadioButtonTemplate")
    hiddenRadio:SetPoint("TOPLEFT", cardTypeLabel, "BOTTOMLEFT", 0, -10)
    hiddenRadio.text:SetText("Hidden")
    hiddenRadio:SetChecked(true)

    local multiRadio = CreateFrame("CheckButton", nil, scrollChild, "UIRadioButtonTemplate")
    multiRadio:SetPoint("LEFT", hiddenRadio, "RIGHT", 80, 0)
    multiRadio.text:SetText("Multi")

    local function CreateScrollingEditBox(parent, width, height)
        -- 1) Create ScrollFrame with backdrop
        local scrollFrame = CreateFrame("ScrollFrame", nil, parent, "UIPanelScrollFrameTemplate, BackdropTemplate")
        scrollFrame:SetSize(width, height)
    
        scrollFrame:SetBackdrop({
            bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
            edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
            edgeSize = 12,
        })
        scrollFrame:SetBackdropBorderColor(0.8, 0.8, 0.8, 1)

        fontPath = "Interface/AddOns/WoWStudy/Fonts/NotoSansCJK-Medium.ttc"
    
        -- 2) Create EditBox
        local editBox = CreateFrame("EditBox", nil, scrollFrame)
        editBox:EnableMouse(true)
        editBox:EnableKeyboard(true)
        editBox:SetAutoFocus(false)
        editBox:SetMultiLine(true)
        editBox:SetMaxLetters(0)
        editBox:SetWidth(width)
        editBox:SetHeight(height)
        editBox:SetFrameLevel(scrollFrame:GetFrameLevel() + 1)
        editBox:SetTextInsets(5, 5, 3, 3)
        editBox:SetPoint("TOPLEFT", 5, -5)
        editBox:SetPoint("BOTTOMRIGHT", -25, 5)
        editBox:SetFont(fontPath, 12, "OUTLINE")
    
        scrollFrame:SetScrollChild(editBox)
    
        editBox:SetScript("OnCursorChanged", function(self, x, y, w, h)
            ScrollingEdit_OnCursorChanged(self, x, y, w, h)
        end)
        editBox:SetScript("OnUpdate", function(self, elapsed)
            ScrollingEdit_OnUpdate(self, elapsed, scrollFrame)
        end)
    
        editBox:SetScript("OnEscapePressed", function(self)
            self:ClearFocus()
        end)
    
        editBox:SetScript("OnMouseDown", function(self, button)
            if button == "LeftButton" then
                self:SetFocus()
            end
        end)
    
        return scrollFrame, editBox
    end
    
    local hiddenQuestionLabel = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    hiddenQuestionLabel:SetText("Question:")
    hiddenQuestionLabel:SetPoint("TOPLEFT", hiddenRadio, "BOTTOMLEFT", 0, -30)

    local hiddenQuestionScroll, hiddenQuestionEditBox = CreateScrollingEditBox(scrollChild, PANEL_WIDTH - 40, 60)
    hiddenQuestionScroll:SetPoint("TOPLEFT", hiddenQuestionLabel, "BOTTOMLEFT", 0, -10)

    local hiddenAnswerLabel = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    hiddenAnswerLabel:SetText("Answer:")
    hiddenAnswerLabel:SetPoint("TOPLEFT", hiddenQuestionScroll, "BOTTOMLEFT", 0, -20)

    local hiddenAnswerScroll, hiddenAnswerEditBox = CreateScrollingEditBox(scrollChild, PANEL_WIDTH - 40, 60)
    hiddenAnswerScroll:SetPoint("TOPLEFT", hiddenAnswerLabel, "BOTTOMLEFT", 0, -10)

    local multiQuestionLabel = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    multiQuestionLabel:SetText("Question:")
    multiQuestionLabel:SetPoint("TOPLEFT", hiddenRadio, "BOTTOMLEFT", 0, -30)

    local multiQuestionScroll, multiQuestionEditBox = CreateScrollingEditBox(scrollChild, PANEL_WIDTH - 40, 60)
    multiQuestionScroll:SetPoint("TOPLEFT", multiQuestionLabel, "BOTTOMLEFT", 0, -10)

    local multiChoices = {}
    for i = 1, 4 do
        local choiceLabel = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        choiceLabel:SetText("Choice " .. i .. ":")
        choiceLabel:SetFont(fontPath, 12)
        if i == 1 then
            choiceLabel:SetPoint("TOPLEFT", multiQuestionScroll, "BOTTOMLEFT", 0, -20)
        else
            choiceLabel:SetPoint("TOPLEFT", multiChoices[i-1].scroll, "BOTTOMLEFT", 0, -30)
        end

        -- Create a scrolling EditBox for each choice
        local choiceScroll, choiceEditBox = CreateScrollingEditBox(scrollChild, PANEL_WIDTH - 40, 40)
        choiceScroll:SetPoint("TOPLEFT", choiceLabel, "BOTTOMLEFT", 0, -10)

        multiChoices[i] = {
            label = choiceLabel,
            scroll = choiceScroll,
            edit   = choiceEditBox,
        }
    end

    local correctChoiceLabel = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    correctChoiceLabel:SetText("Correct Answer # (1-4):")
    correctChoiceLabel:SetPoint("TOPLEFT", multiChoices[4].scroll, "BOTTOMLEFT", 0, -30)

    local correctChoiceEditBox = CreateFrame("EditBox", nil, scrollChild, "InputBoxTemplate")
    correctChoiceEditBox:SetSize(40, 20)
    correctChoiceEditBox:SetPoint("LEFT", correctChoiceLabel, "RIGHT", 10, 0)
    correctChoiceEditBox:SetAutoFocus(false)

    -----------------------------------------------------------------------
    -- Create Card Button
    -----------------------------------------------------------------------
    local createCardButton = CreateFrame("Button", nil, scrollChild, "UIPanelButtonTemplate")
    createCardButton:SetSize(140, 30)
    createCardButton:SetPoint("TOPLEFT", correctChoiceLabel, "BOTTOMLEFT", 0, -40)
    createCardButton:SetText("Create Card")

    createCardButton:SetScript("OnClick", function()
        if not selectedDeck then
            print("No deck selected!")
            return
        end

        if cardType == "hidden" then
            local q = hiddenQuestionEditBox:GetText() or ""
            local a = hiddenAnswerEditBox:GetText() or ""
            if q == "" or a == "" then
                print("Please fill in question and answer (Hidden card).")
                return
            end

            if WoWStudySaved.decks[selectedDeck].cardsByQuestion[q] then
                print("Flashcard already exists in deck:", selectedDeck)
                return
            end

            local card = {
                compositeKey          = selectedDeck .. ":" .. q,
                question              = q,
                answer                = a,
                type                  = "hidden",
                choices               = {},
                lastTime              = 0,
                spacedRepetitionLevel = 0,
                totalCorrect          = 0,
                totalIncorrect        = 0,
                totalAnswered         = 0,
                deckName              = selectedDeck,
                source                = "internal",
                creationTime          = time(),
                history               = {},
                tags                  = {},
            }

            WoWStudySaved.decks[selectedDeck].cardsByQuestion[q] = card

            print("Created card in deck:", selectedDeck)

            WoWStudyFunction.UpdateSelectedFlashcards()

            hiddenQuestionEditBox:SetText("")
            hiddenAnswerEditBox:SetText("")
        else
            local q = multiQuestionEditBox:GetText() or ""
            if q == "" then
                print("Please fill in the multi question.")
                return
            end

            -- Check if flashcard already exists
            if WoWStudySaved.decks[selectedDeck].cardsByQuestion[q] then
                print("Flashcard already exists in deck:", selectedDeck)
                return
            end

            local choices = {}
            for i = 1, 4 do
                choices[i] = multiChoices[i].edit:GetText() or ""
            end

            local correctIndex = tonumber(correctChoiceEditBox:GetText() or "")
            if not correctIndex or correctIndex < 1 or correctIndex > 4 or choices[correctIndex] == "" then
                print("Please provide a valid correct answer index (1-4) and ensure it's not empty.")
                return
            end

            local card = {
                compositeKey          = selectedDeck .. ":" .. q,
                question              = q,
                answer                = choices[correctIndex],
                type                  = "multi",
                choices               = choices,
                lastTime              = 0,
                spacedRepetitionLevel = 0,
                totalCorrect          = 0,
                totalIncorrect        = 0,
                totalAnswered         = 0,
                deckName              = selectedDeck,
                source                = "internal",
                creationTime          = time(),
                history               = {},
                tags                  = {},
            }

            WoWStudySaved.decks[selectedDeck].cardsByQuestion[q] = card

            print("Created card in deck:", selectedDeck)

            WoWStudyFunction.UpdateSelectedFlashcards()

            multiQuestionEditBox:SetText("")
            for i = 1, 4 do
                multiChoices[i].edit:SetText("")
            end
            correctChoiceEditBox:SetText("")
        end
    end)

    -----------------------------------------------------------------------
    -- Show/Hide Fields based on Card Type
    -----------------------------------------------------------------------
    local function UpdateCardFields()
        if cardType == "hidden" then
            -- hide multi fields
            for i = 1, 4 do
                multiChoices[i].label:Hide()
                multiChoices[i].edit:Hide()
                multiChoices[i].scroll:Hide()
            end
            multiQuestionLabel:Hide()
            multiQuestionEditBox:Hide()
            multiQuestionScroll:Hide()
            correctChoiceLabel:Hide()
            correctChoiceEditBox:Hide()
 
            -- show hidden fields
            hiddenQuestionLabel:Show()
            hiddenQuestionEditBox:Show()
            hiddenQuestionScroll:Show()
            hiddenAnswerLabel:Show()
            hiddenAnswerEditBox:Show()
            hiddenAnswerScroll:Show()
            

            -- 2) Anchor the Create button below the hidden fields
            createCardButton:ClearAllPoints()
            createCardButton:SetPoint("TOPLEFT", hiddenAnswerScroll, "BOTTOMLEFT", 0, -40)
        else
            -- multi
            hiddenQuestionLabel:Hide()
            hiddenQuestionEditBox:Hide()
            hiddenQuestionScroll:Hide()
            hiddenAnswerLabel:Hide()
            hiddenAnswerEditBox:Hide()
            hiddenAnswerScroll:Hide()
            

            multiQuestionLabel:Show()
            multiQuestionEditBox:Show()
            for i = 1, 4 do
                multiChoices[i].label:Show()
                multiChoices[i].edit:Show()
                multiChoices[i].scroll:Show()
            end
            multiQuestionScroll:Show()
            correctChoiceLabel:Show()
            correctChoiceEditBox:Show()

            -- 2) Anchor the Create button below the multi fields
            createCardButton:ClearAllPoints()
            createCardButton:SetPoint("TOPLEFT", multiChoices[4].scroll, "BOTTOMLEFT", 0, -50)
        end
    end
    UpdateCardFields()

    hiddenRadio:SetScript("OnClick", function()
        hiddenRadio:SetChecked(true)
        multiRadio:SetChecked(false)
        cardType = "hidden"
        UpdateCardFields()
    end)

    multiRadio:SetScript("OnClick", function()
        hiddenRadio:SetChecked(false)
        multiRadio:SetChecked(true)
        cardType = "multi"
        UpdateCardFields()
    end)

    -----------------------------------------------------------------------
    -- Add Deck Button
    -----------------------------------------------------------------------
    createDeckButton:SetScript("OnClick", function()
        local deckName = deckNameEditBox:GetText()
        if deckName == "" then
            print("Please enter a deck name.")
            return
        end

        if not WoWStudySaved.decks[deckName] then
            local deck = {
                name                         = deckName,
                isSelected                   = true,
                cardsByQuestion              = {},
                source                       = "internal",
                creationTime                 = time(),
                totalCorrect                 = 0,
                totalIncorrect               = 0,
                totalAnswered                = 0,
                tags                         = {},
                deckIcon                     = "",
            }

            WoWStudySaved.decks[deckName] = deck

            UpdateDeckDropdown()
        else
            print("Deck already exists", deckName)
        end

        deckNameEditBox:SetText("")
    end)

    flashcardCreationPanel:SetScript("OnShow", function()
        UpdateDeckDropdown()
    end)

    return flashcardCreationPanel
end
