/*
 * 问卷管理模块：管理题套、启用状态、题目列表、新增与删除。
 * 作者: @ccfork
 */
import { els, setMobileView } from './state.js';
import { escapeHtml, plainQuestionText } from './utils.js';

const questionnaireApi = 'admin/api/questionnaire.php';
let questionnaireStore = { active_set_id: null, active_set: null, sets: [], questions: [] };

async function questionnaireGet(params = {}) {
    const query = new URLSearchParams(params);
    const res = await fetch(`${questionnaireApi}?${query.toString()}`, { cache: 'no-store' });
    return await res.json();
}

async function questionnairePost(payload) {
    const res = await fetch(questionnaireApi, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    });
    return await res.json();
}

function applyStore(data) {
    questionnaireStore = {
        active_set_id: data.active_set_id || questionnaireStore.active_set_id,
        active_set: data.active_set || questionnaireStore.active_set,
        sets: data.sets || questionnaireStore.sets,
        questions: data.questions || questionnaireStore.questions
    };
}

function currentSet() {
    return questionnaireStore.active_set || {
        id: 'default',
        title: '小问卷',
        enabled: true,
        questions: questionnaireStore.questions || []
    };
}

function renderSetList() {
    const sets = questionnaireStore.sets || [];
    els.questionnaireSetSelect.innerHTML = sets.map((set) => (
        `<option value="${escapeHtml(set.id)}"${set.id === questionnaireStore.active_set_id ? ' selected' : ''}>${escapeHtml(set.title)}${set.enabled ? '' : '（关闭）'}</option>`
    )).join('');
    els.questionnaireTitleInput.value = currentSet().title || '';
    els.questionnaireEnabledInput.checked = !!currentSet().enabled;
}

function renderQuestionList() {
    const questions = currentSet().questions || [];
    if (!questions.length) {
        els.questionList.innerHTML = '<div class="empty-state">还没有题目～</div>';
        return;
    }
    els.questionList.innerHTML = questions.map((question, index) => `
        <div class="question-card question-edit-card" data-id="${escapeHtml(question.id)}" data-index="${index}">
            <div class="question-order">第 ${index + 1} 题</div>
            <label class="field-label">题目</label>
            <textarea class="question-edit-text" data-field="question-text">${escapeHtml(plainQuestionText(question.text))}</textarea>
            <label class="field-label">题型</label>
            <select class="question-edit-type" data-field="question-type">
                <option value="single"${question.type !== 'multi' ? ' selected' : ''}>单选</option>
                <option value="multi"${question.type === 'multi' ? ' selected' : ''}>多选</option>
            </select>
            <label class="field-label">选项（每行一个）</label>
            <textarea class="question-edit-options" data-field="question-options">${escapeHtml((question.options || []).map((option) => option.label).join('\n'))}</textarea>
            <div class="question-card-actions">
                <button class="cute-btn" type="button" data-action="save-question">保存题目</button>
                <button class="cute-btn danger-btn" type="button" data-action="delete-question">删除题目</button>
            </div>
        </div>
    `).join('');
}

export async function loadQuestionnaire() {
    const data = await questionnaireGet({ action: 'get' });
    if (!data.success) return;
    applyStore(data);
    renderSetList();
    renderQuestionList();
}

export function openQuestionnairePanel() {
    els.questionnairePanel.classList.add('active');
    els.resultsPanel.classList.remove('active');
    els.adminShell.classList.add('has-questionnaire');
    els.adminShell.classList.remove('has-results');
    setMobileView('questionnaire');
    loadQuestionnaire();
}

function closeQuestionnairePanel() {
    els.questionnairePanel.classList.remove('active');
    els.adminShell.classList.remove('has-questionnaire');
    setMobileView('chat');
}

async function saveAndRender(payload) {
    const data = await questionnairePost(payload);
    if (!data.success) {
        alert(data.error || '操作失败');
        return false;
    }
    applyStore(data);
    renderSetList();
    renderQuestionList();
    return true;
}

async function addQuestion() {
    const text = els.newQuestionText.value.trim();
    const options = els.newQuestionOptions.value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean);
    if (!text) {
        alert('先写题目哦');
        return;
    }
    const ok = await saveAndRender({ action: 'add_question', text, options });
    if (ok) {
        els.newQuestionText.value = '';
        els.newQuestionOptions.value = '';
    }
}

async function deleteQuestion(id) {
    if (!confirm('确定删除这道题吗？')) return;
    await saveAndRender({ action: 'delete_question', id });
}

async function saveQuestion(card) {
    const questions = currentSet().questions || [];
    const index = Number(card.dataset.index);
    const question = questions[index];
    if (!question) return;
    const text = card.querySelector('[data-field="question-text"]').value.trim();
    const type = card.querySelector('[data-field="question-type"]').value;
    const labels = card.querySelector('[data-field="question-options"]').value
        .split(/\r?\n/)
        .map((item) => item.trim())
        .filter(Boolean);
    const oldOptions = question.options || [];
    // 编辑选项文本时保留原 value/跳转/跳过标记，避免影响已有跳题逻辑。
    const options = labels.map((label, optionIndex) => ({
        ...(oldOptions[optionIndex] || {}),
        label,
        value: oldOptions[optionIndex]?.value ?? (type === 'multi' ? `option_${optionIndex + 1}` : optionIndex + 1)
    }));
    await saveAndRender({ action: 'update_question', id: question.id, text, type, options });
}

async function setEnabled() {
    await saveAndRender({ action: 'set_enabled', enabled: els.questionnaireEnabledInput.checked });
}

async function saveQuestionnaireTitle() {
    await saveAndRender({ action: 'set_title', title: els.questionnaireTitleInput.value.trim() });
}

async function switchQuestionnaireSet() {
    await saveAndRender({ action: 'set_active_set', set_id: els.questionnaireSetSelect.value });
}

async function createQuestionnaireSet() {
    const title = els.newQuestionnaireTitleInput.value.trim() || '新问卷';
    const ok = await saveAndRender({ action: 'create_set', title, copy_current: false });
    if (ok) els.newQuestionnaireTitleInput.value = '';
}

async function deleteQuestionnaireSet() {
    if (!confirm('确定删除当前题套吗？')) return;
    await saveAndRender({ action: 'delete_set', set_id: questionnaireStore.active_set_id });
}

export function bindQuestionnairePanel() {
    els.questionnaireManageBtn.addEventListener('click', openQuestionnairePanel);
    els.closeQuestionnaireBtn.addEventListener('click', closeQuestionnairePanel);
    els.addQuestionBtn.addEventListener('click', addQuestion);
    els.questionnaireEnabledInput.addEventListener('change', setEnabled);
    els.saveQuestionnaireTitleBtn.addEventListener('click', saveQuestionnaireTitle);
    els.questionnaireSetSelect.addEventListener('change', switchQuestionnaireSet);
    els.createQuestionnaireSetBtn.addEventListener('click', createQuestionnaireSet);
    els.deleteQuestionnaireSetBtn.addEventListener('click', deleteQuestionnaireSet);
    els.questionList.addEventListener('click', (event) => {
        const saveButton = event.target.closest('[data-action="save-question"]');
        if (saveButton) {
            const card = saveButton.closest('.question-card');
            if (card) saveQuestion(card);
            return;
        }
        const button = event.target.closest('[data-action="delete-question"]');
        if (!button) return;
        const card = button.closest('.question-card');
        if (card) deleteQuestion(card.dataset.id);
    });
}
