import type Config from '../../types/config';
import type GPTAnswer from '../../types/gpt-answer';
import type { DragDropTextResponse } from '../../types/question-types';
import { MoodleQuestionType } from '../../types/question-types';

export default function handleDragDropText(
  config: Config,
  inputList: NodeListOf<HTMLElement>,
  gptAnswer: GPTAnswer
): boolean {
  if (!gptAnswer.response || gptAnswer.response.question_type !== MoodleQuestionType.DRAG_DROP_TEXT)
    return false;

  const response = gptAnswer.response as DragDropTextResponse;
  const hiddenInputs = Array.from(inputList).filter(el =>
    el.classList.contains('placeinput')
  ) as HTMLInputElement[];

  for (const answer of response.correct_answers) {
    const hiddenInput = hiddenInputs[answer.blank_index];
    if (!hiddenInput) continue;

    const container = hiddenInput.closest('.que');
    if (!container) continue;

    const dragHomes = container.querySelectorAll('.draghome.unplaced');
    const targetDrag = dragHomes[answer.draggable_index];
    if (!targetDrag) continue;

    const choiceMatch = targetDrag.className.match(/choice(\d+)/);
    if (!choiceMatch) continue;

    const choiceValue = choiceMatch[1];
    hiddenInput.value = choiceValue;

    // visually update the drag drop UI string
    const blankSpan = container.querySelector(`.place${answer.blank_index + 1}.drop`);
    if (blankSpan) {
      blankSpan.textContent = targetDrag.textContent;
    }
  }

  return true;
}
