"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Question, QuizAnswer } from "@/types/quiz";

interface ResultItem {
  question: Question;
  selectedAnswers: string[];
  correct: boolean;
}

export default function QuizResultsPage() {
  const router = useRouter();
  const [results, setResults] = useState<ResultItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [duration, setDuration] = useState<string | null>(null);

  useEffect(() => {
    const answersStr = sessionStorage.getItem("quizAnswers");
    const questionsStr = sessionStorage.getItem("quizQuestions");

    if (!answersStr || !questionsStr) {
      router.push("/quiz");
      return;
    }

    const startedAt = sessionStorage.getItem("quizStartedAt");
    const finishedAt = sessionStorage.getItem("quizFinishedAt");
    if (startedAt && finishedAt) {
      const ms = new Date(finishedAt).getTime() - new Date(startedAt).getTime();
      const totalSeconds = Math.floor(ms / 1000);
      const hours = Math.floor(totalSeconds / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;
      if (hours > 0) setDuration(`${hours}h ${minutes}m ${seconds}s`);
      else if (minutes > 0) setDuration(`${minutes}m ${seconds}s`);
      else setDuration(`${seconds}s`);
    }

    const answers: QuizAnswer[] = JSON.parse(answersStr);
    const questions: Question[] = JSON.parse(questionsStr);

    const items: ResultItem[] = questions.map((q) => {
      const answer = answers.find((a) => a.questionId === q.id);
      const selected = answer?.selectedAnswers || [];

      let correct: boolean;
      if (q.type === "multiple-dropdown") {
        correct = (q.subQuestions || []).every((sq) => {
          const entry = selected.find((a) => a.startsWith(sq.id + ":"));
          return entry ? entry.split(":")[1] === sq.correctOptionId : false;
        });
      } else {
        correct =
          selected.length === q.correctAnswers.length &&
          selected.every((s) => q.correctAnswers.includes(s));
      }

      return { question: q, selectedAnswers: selected, correct };
    });

    setResults(items);
    setLoading(false);
  }, [router]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <p className="text-gray-500">Loading results...</p>
      </div>
    );
  }

  const correctCount = results.filter((r) => r.correct).length;
  const percentage = Math.round((correctCount / results.length) * 100);

  return (
    <div className="min-h-screen bg-gray-50">
      <header className="border-b bg-white px-6 py-4">
        <h1 className="text-xl font-bold text-gray-900 text-center">
          Quiz Results
        </h1>
      </header>

      <main className="max-w-3xl mx-auto p-6 space-y-6">
        <div className="bg-white rounded-xl p-8 text-center shadow-sm">
          <div
            className={`text-6xl font-bold mb-2 ${
              percentage >= 70
                ? "text-green-600"
                : percentage >= 50
                ? "text-yellow-600"
                : "text-red-600"
            }`}
          >
            {percentage}%
          </div>
          <p className="text-gray-600">
            You got {correctCount} out of {results.length} questions correct
          </p>
          {duration && (
            <p className="text-sm text-gray-400 mt-1">
              Time: {duration}
            </p>
          )}
        </div>

        <div className="space-y-4">
          <h2 className="text-lg font-semibold text-gray-900">Review</h2>
          {results.map((item, i) => (
            <div
              key={item.question.id}
              className={`p-4 rounded-lg border ${
                item.correct
                  ? "bg-green-50 border-green-200"
                  : "bg-red-50 border-red-200"
              }`}
            >
              <div className="flex items-start gap-3">
                <span
                  className={`mt-0.5 text-lg ${
                    item.correct ? "text-green-600" : "text-red-600"
                  }`}
                >
                  {item.correct ? "✓" : "✗"}
                </span>
                <div className="flex-1">
                  <p className="font-medium text-gray-900">
                    {i + 1}. {item.question.text}
                  </p>
                  <div className="mt-2 space-y-1">
                    {item.question.type === "multiple-dropdown" ? (
                      (item.question.subQuestions || []).map((sq) => {
                        const entry = item.selectedAnswers.find((a) => a.startsWith(sq.id + ":"));
                        const selectedOptId = entry ? entry.split(":")[1] : "";
                        const selectedOpt = (sq.options || []).find((o) => o.id === selectedOptId);
                        const correctOpt = (sq.options || []).find((o) => o.id === sq.correctOptionId);
                        const isCorrect = selectedOptId === sq.correctOptionId;

                        return (
                          <div key={sq.id} className="text-sm flex items-start gap-2">
                            {isCorrect ? (
                              <span className="text-green-600">✓</span>
                            ) : (
                              <span className="text-red-600">✗</span>
                            )}
                            <div>
                              <span className="text-gray-700">{sq.text}</span>
                              <span className={`ml-2 ${isCorrect ? "text-green-700 font-medium" : "text-red-600"}`}>
                                → {selectedOpt?.label || "(no answer)"}
                              </span>
                              {!isCorrect && correctOpt && (
                                <span className="ml-2 text-green-700 font-medium">
                                  (correct: {correctOpt.label})
                                </span>
                              )}
                            </div>
                          </div>
                        );
                      })
                    ) : (
                    item.question.options.map((opt) => {
                      const isCorrect =
                        item.question.correctAnswers.includes(opt.id);
                      const wasSelected =
                        item.selectedAnswers.includes(opt.id);

                      return (
                        <div
                          key={opt.id}
                          className={`text-sm flex items-center gap-2 ${
                            isCorrect
                              ? "text-green-700 font-medium"
                              : wasSelected
                              ? "text-red-600 line-through"
                              : "text-gray-500"
                          }`}
                        >
                          {isCorrect && <span>✓</span>}
                          {wasSelected && !isCorrect && <span>✗</span>}
                          {!isCorrect && !wasSelected && (
                            <span className="w-3" />
                          )}
                          <span>{opt.label}</span>
                        </div>
                      );
                    })
                    )}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>

        <div className="flex gap-3">
          <button
            onClick={() => router.push("/quiz")}
            className="flex-1 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium"
          >
            Take Another Quiz
          </button>
        </div>
      </main>
    </div>
  );
}
