"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  CheckCircle2Icon,
  AlertTriangleIcon,
  ArrowRightIcon,
  ArrowLeftIcon,
  Loader2Icon,
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { type ExamQuestionSummary, submitExamSection } from "@/lib/api/exams";
import { renderRemarkInline } from "@/lib/remark-inline";
import { useLocaleFunction } from "@/hooks/use-localed";


interface SubmitConfirmationProps {
  examId: number;
  examAttemptId: number;
  sectionId: number;
  summaries: ExamQuestionSummary[];
}

export default function SubmitConfirmationContent({
  examId,
  examAttemptId,
  sectionId,
  summaries,
}: SubmitConfirmationProps) {
  const router = useRouter();
  const t = useLocaleFunction();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const answeredCount = summaries.filter((q) => q.is_answered).length;
  const unansweredCount = summaries.length - answeredCount;
  const unansweredQuestions = summaries.filter((q) => !q.is_answered); 

  const handleSubmitExam = async () => {
    if (isSubmitting) return;
    setIsSubmitting(true);

    try {
      await submitExamSection(examAttemptId, sectionId);
    } catch (error) {
      setIsSubmitting(false);
      console.error("Failed to submit exam section:", error);
    } finally {
      router.replace(`/exam/${examId}/result`);
    }
  };

  const handleContinueExam = async () => {
    if (isSubmitting) return;
    router.replace(`/exam/${examId}/question/1`);
  };

  const handleGoToQuestion = (questionIndex: number) => {
    router.replace(`/exam/${examId}/question/${questionIndex}`);
  };

  return (
    <div className="flex justify-center">
      <Card>
        <CardHeader className="text-center">
          <div className="w-16 h-16 rounded-full bg-muted mx-auto flex items-center justify-center mb-4">
            <CheckCircle2Icon className="h-8 w-8 text-muted-foreground" />
          </div>
          <CardTitle className="text-2xl mb-2">
            {t("exam.submit_confirmation.title")}
          </CardTitle>
          <p className="text-muted-foreground [&_b]:text-foreground">
            {renderRemarkInline(t("exam.submit_confirmation.description"), true)}
          </p>
        </CardHeader>
        <CardContent>
          <div className="bg-muted rounded p-4 mb-6">
            <div className="flex items-center justify-between">
              <span className="text-sm text-muted-foreground">
                {t("exam.submit_confirmation.answered_count")}
              </span>
              <span className="text-lg font-semibold text-foreground">
                <span className="text-success">{answeredCount}</span> /{" "}
                {summaries.length}
              </span>
            </div>
          </div>
          {unansweredQuestions.length > 0 && (
            <div className="border border-warning/30 bg-warning/5 rounded p-4 mb-6">
              <div className="flex items-start gap-3 mb-3">
                <AlertTriangleIcon className="w-5 h-5 text-warning flex-shrink-0 mt-0.5" />
                <div>
                  <p className="font-medium text-foreground">
                    {t(
                      "exam.submit_confirmation.unanswered_count",
                      unansweredQuestions.length,
                      `question${unansweredCount > 1 ? "s" : ""}`
                    )}
                  </p>
                  <p className="text-sm text-muted-foreground">
                    {t("exam.submit_confirmation.unanswered_description")}
                  </p>
                </div>
              </div>
              <div className="flex flex-wrap gap-2">
                {unansweredQuestions.map((q) => (
                  <button
                    key={q.display_order}
                    onClick={() => handleGoToQuestion(q.display_order + 1)}
                    className="w-8 h-8 rounded cursor-pointer bg-warning/20 text-warning hover:bg-warning/30 text-sm font-medium exam-transition"
                  >
                    {q.display_order + 1}
                  </button>
                ))}
              </div>
            </div>
          )}
          {/* All answered */}
          {unansweredCount === 0 && (
            <div className="border border-success/30 bg-success/5 rounded p-4 mb-6">
              <div className="flex items-center gap-3">
                <CheckCircle2Icon className="w-5 h-5 text-success" />
                <p className="font-medium text-foreground">
                  {t("exam.submit_confirmation.all_answered")}
                </p>
              </div>
            </div>
          )}

          {/* Actions */}
          <div className="flex items-center justify-between pt-4">
            <Button
              variant="outline"
              size="lg"
              className="cursor-pointer"
              onClick={handleContinueExam}
              disabled={isSubmitting}
            >
              <ArrowLeftIcon className="w-4 h-4 mr-2" />
              {t("exam.submit_confirmation.review_answers")}
            </Button>
            <Button
              size="lg"
              className="cursor-pointer"
              onClick={handleSubmitExam}
              disabled={isSubmitting}
            >
              {t("exam.submit_confirmation.submit_exam")}
              {isSubmitting ?
                (<Loader2Icon className="w-4 h-4 ml-2 animate-spin" />)
                : (<ArrowRightIcon className="w-4 h-4 ml-2" />)}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
