import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroupItem } from "@/components/ui/radio-group";
import { useLocaleFunction } from "@/hooks/use-localed";
import type { QuizPart } from "@/lib/api/labs.v2";
import { renderRemarkInline } from "@/lib/remark-inline";
import { cn } from "@/lib/utils";
import { CheckIcon, XIcon } from "lucide-react";
import { RadioGroup } from "radix-ui";
import { type SetStateAction, useId } from "react";

type Question = QuizPart["content"]["questions"][number];

const listItem = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];

export function QuizQuestion({
  question,
  disabled,
  value,
  onValueChange,
  isCorrect,
  explanation,
  correctAnswer,
}: {
  question: Question;
  disabled?: boolean;
  value: number[];
  onValueChange: (value: SetStateAction<number[]>) => void;
  isCorrect?: boolean;
  explanation?: string;
  correctAnswer?: number[];
}) {
  const id = useId();
  const questionContent = renderRemarkInline(question.question);
  const t = useLocaleFunction();

  let el = (
    <li
      className={cn(
        "relative marker:text-muted-foreground",
        isCorrect === false && "marker:text-destructive [&>p]:text-destructive",
        typeof isCorrect === "boolean" ? "[&>:nth-child(2)]:pl-7" : ""
      )}
      data-is-correct={
        isCorrect === true ? "true" : isCorrect === false ? "false" : undefined
      }
    >
      {isCorrect === true && (
        <CheckIcon className="absolute size-4 left-1 top-1 text-green-500" />
      )}
      {isCorrect === false && (
        <XIcon className="absolute size-4 left-1 top-1 text-destructive" />
      )}
      {questionContent}
      {(explanation || correctAnswer) && (
        <blockquote>
          {correctAnswer && (
            <p>
              {t(
                "lab.quiz.correct-answer",
                correctAnswer
                  .map(
                    (id) =>
                      listItem[question.options.findIndex((op) => op.id === id)]
                  )
                  .join(", ")
              )}
            </p>
          )}
          {explanation && renderRemarkInline(explanation)}
        </blockquote>
      )}
      <ol className="pl-0!">
        {question.options.map((option, index) => (
          <li key={option.id} className="marker:leading-6 list-none">
            <div className="flex gap-1">
              <div className="h-6 flex items-center justify-center">
                {question.type === "MultipleChoice" ? (
                  <Checkbox
                    id={id + "-" + option.id}
                    disabled={disabled}
                    checked={value?.includes(option.id)}
                    onCheckedChange={(checked) => {
                      onValueChange((prev) => {
                        if (checked) {
                          if (!prev.includes(option.id)) {
                            return [...prev, option.id];
                          }
                        } else {
                          if (prev.includes(option.id)) {
                            return prev.filter((id) => id !== option.id);
                          }
                        }
                        return prev;
                      });
                    }}
                  />
                ) : (
                  <RadioGroupItem
                    id={id + "-" + option.id}
                    value={option.id.toString()}
                  />
                )}
              </div>
              <label
                className="flex-1 flex gap-1"
                htmlFor={id + "-" + option.id}
              >
                <span className="leading-6 font-semibold select-none">
                  {listItem[index]}.
                </span>
                <div className="flex-1">{renderRemarkInline(option.text)}</div>
              </label>
            </div>
          </li>
        ))}
      </ol>
    </li>
  );

  if (question.type === "SingleChoice") {
    el = (
      <RadioGroup.Root
        asChild
        disabled={disabled}
        value={value[0]?.toString(10) ?? ""}
        onValueChange={(value) => {
          if (value.length > 0) {
            onValueChange([parseInt(value)]);
          }
        }}
      >
        {el}
      </RadioGroup.Root>
    );
  }

  return el;
}
