"use client";

import { useState } from "react";
import { ArrowRightIcon, ArrowLeftIcon, Loader2Icon } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import Markdown from "@/components/markdown/markdown";
import { renderRemarkInline } from "@/lib/remark-inline";
import { type ExamQuestion } from "@/lib/api/exams";
import { useLocaleFunction } from "@/hooks/use-localed";

interface QuestionNavProps {
  isLoading: boolean;
  question: ExamQuestion;
  questionNum: number;
  total: number;
  answer: number[];
  onAnswerChange: (value: number[]) => void;
  onSubmitExam: () => void;
  onPreviousQuestion: () => void;
  onNextQuestion: () => void;
}

export default function QuestionCard({
  isLoading,
  question,
  questionNum,
  total,
  answer,
  onAnswerChange,
  onSubmitExam,
  onPreviousQuestion,
  onNextQuestion,
}: QuestionNavProps) {
  const t = useLocaleFunction();

  const selectedValues = Array.isArray(answer) ? answer : [];
  const [isSubmitting, setIsSubmitting] = useState(false);

  return (
    <div className="relative">
      {isLoading && (
        <div className="absolute inset-0 z-1 bg-background/60 flex items-center justify-center">
          <Loader2Icon className="animate-spin" />
        </div>
      )}

      <Card>
        <CardHeader>
          <div className="mb-2 flex items-center gap-2 text-sm text-muted-foreground">
            {question.question_type === 1 ? (
              <span className="rounded bg-accent px-2 py-1 text-xs font-medium text-accent-foreground">
                {t("exam.question.multiple_select")}
              </span>
            ) : (
              <span className="rounded bg-accent px-2 py-1 text-xs font-medium text-accent-foreground">
                {t("exam.question.single_select")}
              </span>
            )}
          </div>
          {/* <CardTitle className="text-xl font-bold">
            Question {questionNum}: {renderRemarkInline(question.stem, true)}
          </CardTitle> */}
          <CardTitle className="text-xl [&_p]:text-xl">
            <Markdown enableAIExplain={false}>{renderRemarkInline(question.stem)}</Markdown>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div>
            {question.question_type === 0 && (
              <RadioGroup
                value={
                  answer[0] !== undefined ? answer[0].toString() : ""
                }
                onValueChange={(value) => {
                  onAnswerChange([parseInt(value, 10)]);
                }}
                className="gap-6"
              >
                {question.content.map((option) => (
                  <div
                    key={option.id}
                    className="flex gap-3 items-start rounded border p-4 hover:bg-accent"
                  >
                    <RadioGroupItem
                      value={option.id.toString()}
                      id={`option-${option.id}`}
                      className="mt-1"
                    />
                    <Label
                      className="flex-1 text-base font-semibold cursor-pointer"
                      htmlFor={`option-${option.id}`}
                    >
                      {option.text}
                    </Label>
                  </div>
                ))}
              </RadioGroup>
            )}

            {question.question_type === 1 && (
              <div className="flex flex-col gap-6">
                {question.content.map((option) => {
                  return (
                    <div
                      key={option.id}
                      className="flex gap-3 items-start rounded border p-4 hover:bg-accent"
                    >
                      <Checkbox
                        id={`checkbox-${option.id}`}
                        className="mt-1"
                        checked={selectedValues.includes(option.id)}
                        onCheckedChange={(checked) => {
                          const next = checked
                            ? [...selectedValues, option.id]
                            : selectedValues.filter((id) => id !== option.id);

                          onAnswerChange(next);
                        }}
                      />
                      <Label
                        className="flex-1 text-base font-semibold cursor-pointer"
                        htmlFor={`checkbox-${option.id}`}
                      >
                        {option.text}
                      </Label>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </CardContent>
      </Card>
      <div className="mt-6 flex flex-row-reverse justify-between">
        {questionNum < total ? (
          <Button onClick={onNextQuestion} className="cursor-pointer" size="lg">
            {t("exam.question.next")}
            <ArrowRightIcon className="w-4 h-4 ml-2" />
          </Button>
        ) : (
          <Button
            className="cursor-pointer"
            onClick={async () => {
              setIsSubmitting(true);
              try {
                onSubmitExam();
              } catch (error) {
                console.error("Failed to submit exam:", error);
                setIsSubmitting(false);
              }
            }}
            disabled={isSubmitting}
            size="lg"
          >
            {t("exam.question.submit")}
            {isSubmitting ?
              (<Loader2Icon className="w-4 h-4 ml-2 animate-spin" />)
              : (<ArrowRightIcon className="w-4 h-4 ml-2" />)}
          </Button>
        )}
        {questionNum !== 1 && (
          <Button
            variant="outline"
            onClick={onPreviousQuestion}
            className="cursor-pointer"
            size="lg"
          >
            <ArrowLeftIcon className="w-4 h-4 mr-2" />
            {t("exam.question.previous")}
          </Button>
        )}
      </div>
    </div>
  );
}
