import type { QuizOption, QuizQuestion, Word } from '../api/request'
import { spellQuestionFromWord } from './spellQuestion'

function enText(w: Word) {
  return w.source_lang === 'en' ? w.source_text : w.target_text
}

function zhText(w: Word) {
  return w.source_lang === 'zh' ? w.source_text : w.target_text
}

function shuffle<T>(arr: T[]): T[] {
  const a = [...arr]
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[a[i], a[j]] = [a[j], a[i]]
  }
  return a
}

export type PracticeMode = 'en_to_zh' | 'zh_to_en' | 'spell'

export function buildPracticeQuestion(
  word: Word,
  pool: Word[],
  mode: PracticeMode
): QuizQuestion {
  if (mode === 'spell') {
    return spellQuestionFromWord(word)
  }

  const others = pool.filter((w) => w.id !== word.id)
  if (mode === 'en_to_zh') {
    const prompt = enText(word)
    const correct = zhText(word)
    const distractors = shuffle(
      others.map((w) => zhText(w)).filter((t) => t !== correct)
    ).slice(0, 3)
    const optionsText = shuffle([correct, ...distractors])
    const labels = ['A', 'B', 'C', 'D']
    const options: QuizOption[] = optionsText.slice(0, 4).map((text, i) => ({
      label: labels[i],
      text,
    }))
    return {
      word_id: word.id,
      question_type: 'en_to_zh',
      prompt,
      options,
      correct_answer: correct,
    }
  }

  const prompt = zhText(word)
  const correct = enText(word)
  const distractors = shuffle(
    others.map((w) => enText(w)).filter((t) => t !== correct)
  ).slice(0, 3)
  const optionsText = shuffle([correct, ...distractors])
  const labels = ['A', 'B', 'C', 'D']
  const options: QuizOption[] = optionsText.slice(0, 4).map((text, i) => ({
    label: labels[i],
    text,
  }))
  return {
    word_id: word.id,
    question_type: 'zh_to_en',
    prompt,
    options,
    correct_answer: correct,
  }
}
