import { MoodleQuestionQuery, MoodleQuestionType, AnswerOption } from '../types/question-types';
import normalizeText from 'background/utils/normalize-text';

/**
 * Extracts options from a multichoice question.
 */
function extractOptions(questionElement: HTMLElement, inputSelector: string): AnswerOption[] {
  const options: AnswerOption[] = [];
  const inputs = questionElement.querySelectorAll<HTMLInputElement>(inputSelector);

  inputs.forEach((input, index) => {
    // some inputs have value "-1", which is standard moodle for "clear choice"
    if (input.value === '-1') return;

    // Try finding the label by ID
    let text = '';
    const labelEl = questionElement.querySelector(`#${input.id.replace(/:/g, '\\:')}_label`);
    if (labelEl) {
      text = labelEl.textContent ?? '';
    } else {
      text = input.parentElement?.textContent ?? '';
    }

    text = normalizeText(text.replace('Clear my choice', ''));
    if (text) {
      options.push({
        index,
        text
      });
    }
  });

  return options;
}

/**
 * Parse the question DOM element to determine the strict question type and structural query
 * @param questionElement The question container element
 * @param normalizedQuestionText The full text of the question
 * @returns MoodleQuestionQuery object or null if parsing fails
 */
export function parseMoodleQuestion(
  questionElement: HTMLElement,
  normalizedQuestionText: string
): MoodleQuestionQuery | null {
  const container =
    questionElement.closest('.que') || questionElement.closest('.formulation') || questionElement;

  if (
    container.classList.contains('multichoice') ||
    container.classList.contains('calculatedmulti')
  ) {
    const checkboxes = container.querySelectorAll<HTMLInputElement>(
      '.answer input[type="checkbox"]'
    );
    const radios = container.querySelectorAll<HTMLInputElement>('.answer input[type="radio"]');

    if (checkboxes.length > 0) {
      return {
        question_type: MoodleQuestionType.MULTIPLE_CHOICE,
        question_text: normalizedQuestionText,
        answer_options: extractOptions(container as HTMLElement, '.answer input[type="checkbox"]')
      };
    } else if (radios.length > 0) {
      return {
        question_type: MoodleQuestionType.SINGLE_CHOICE,
        question_text: normalizedQuestionText,
        answer_options: extractOptions(container as HTMLElement, '.answer input[type="radio"]')
      };
    }
  }

  if (container.classList.contains('truefalse')) {
    return {
      question_type: MoodleQuestionType.TRUE_FALSE,
      question_text: normalizedQuestionText
    };
  }

  if (container.classList.contains('shortanswer')) {
    return {
      question_type: MoodleQuestionType.SHORT_TEXT,
      question_text: normalizedQuestionText
    };
  }

  if (
    container.classList.contains('numerical') ||
    container.classList.contains('calculated') ||
    container.classList.contains('calculatedsimple')
  ) {
    return {
      question_type: MoodleQuestionType.NUMERICAL,
      question_text: normalizedQuestionText
    };
  }

  if (container.classList.contains('essay')) {
    let format: 'plain_text' | 'html' = 'plain_text';
    let initial_text = '';

    const editorDiv = container.querySelector('.qtype_essay_editor');
    if (editorDiv) format = 'html';

    const textarea = container.querySelector<HTMLTextAreaElement>('textarea');
    if (textarea) {
      initial_text = textarea.value || textarea.textContent || '';
      initial_text = normalizeText(initial_text);
    }

    const payload: MoodleQuestionQuery = {
      question_type: MoodleQuestionType.ESSAY,
      question_text: normalizedQuestionText,
      format
    };
    if (initial_text) {
      (payload as any).initial_text = initial_text;
    }

    return payload;
  }

  if (container.classList.contains('match')) {
    const subQuestions: { index: number; text: string }[] = [];
    const firstSelectOptions: { index: number; text: string }[] = [];

    const rows = container.querySelectorAll('tr');
    let subIndex = 0;
    rows.forEach(row => {
      const textCell = row.querySelector('.text');
      const select = row.querySelector('select');
      if (textCell && select) {
        subQuestions.push({ index: subIndex, text: normalizeText(textCell.textContent || '') });
        if (subIndex === 0) {
          const options = select.querySelectorAll('option');
          let optionIndexCounter = 0;
          Array.from(options)
            .slice(1)
            .forEach(opt => {
              firstSelectOptions.push({
                index: optionIndexCounter++,
                text: normalizeText(opt.textContent || '')
              });
            });
        }
        subIndex++;
      }
    });

    return {
      question_type: MoodleQuestionType.MATCH,
      question_text: normalizedQuestionText,
      sub_questions: subQuestions,
      options: firstSelectOptions
    };
  }

  if (container.classList.contains('gapselect')) {
    const selects = container.querySelectorAll('select');
    const dropDowns: { index: number; options: { index: number; text: string }[] }[] = [];

    selects.forEach((select, dropIndex) => {
      const options = select.querySelectorAll('option');
      const optArr: { index: number; text: string }[] = [];
      let optionIndexCounter = 0;
      Array.from(options)
        .slice(1)
        .forEach(opt => {
          optArr.push({ index: optionIndexCounter++, text: normalizeText(opt.textContent || '') });
        });
      dropDowns.push({ index: dropIndex, options: optArr });
    });

    return {
      question_type: MoodleQuestionType.SELECT_MISSING_WORD,
      question_text: normalizedQuestionText,
      drop_downs: dropDowns
    };
  }

  if (container.classList.contains('ddwtos')) {
    const dragContainer = container.querySelector('.answercontainer');
    const draggables: { index: number; text: string }[] = [];
    if (dragContainer) {
      const dragHomes = dragContainer.querySelectorAll('.draghome.unplaced');
      dragHomes.forEach((drag, idx) => {
        draggables.push({ index: idx, text: normalizeText(drag.textContent || '') });
      });
    }

    return {
      question_type: MoodleQuestionType.DRAG_DROP_TEXT,
      question_text: normalizedQuestionText,
      draggables
    };
  }

  if (container.classList.contains('ordering')) {
    const itemsContainer = container.querySelector('.sortablelist');
    const orderingItems: { index: number; text: string }[] = [];
    if (itemsContainer) {
      const items = itemsContainer.querySelectorAll('.sortableitem');
      items.forEach((item, idx) => {
        // the textcontent holds the answer string or possibly img alt depending on the question contents
        let text = item.textContent?.trim() || '';
        // If it's an image-only answering scenario, text will be empty, grab the alt of first img
        if (text === '') {
          const img = item.querySelector('img');
          if (img) text = img.getAttribute('alt') || '';
        }
        orderingItems.push({ index: idx, text: normalizeText(text) });
      });
    }

    return {
      question_type: MoodleQuestionType.ORDERING,
      question_text: normalizedQuestionText,
      items: orderingItems
    };
  }

  return null;
}
