"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { ArrowLeft, LocateIcon } from "lucide-react";
import { useEffect } from "react";

// Types
interface Question {
  question: string;
  options: Record<string, string>;
  correctAnswer: string;
  userAnswer: string | null;
  isCorrect: boolean;
  solution: string;
}

interface ResultSheet {
  score: number;
  questions: Question[];
}

const ResultsPage = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const answersParam = searchParams.get("answers");

  if (!answersParam) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">
            No results found
          </h2>
          <button
            onClick={() => router.push("/unit")}
            className="bg-blue-900 text-white px-6 py-3 rounded-lg font-semibold hover:bg-blue-800 transition-colors"
          >
            Go Back
          </button>
        </div>
      </div>
    );
  }

  const resultSheet: ResultSheet = JSON.parse(decodeURIComponent(answersParam));

  const getScoreMessage = (score: number) => {
    if (score < 30) return "Try harder!";
    if (score < 70) return "Getting Better";
    return "You did great!";
  };

  const getStatusColor = (question: Question) => {
    if (question.userAnswer === null) return "bg-yellow-500";
    return question.isCorrect ? "bg-green-500" : "bg-red-500";
  };

  const getStatusText = (question: Question) => {
    if (question.userAnswer === null) return "Skipped";
    return question.isCorrect ? "Correct" : "Incorrect";
  };

  const getOptionClassName = (key: string, question: Question): string => {
    const isCorrectAnswer = key === question.correctAnswer;
    const isUserAnswer = key === question.userAnswer;
    const isCorrectAndUserAnswer = isCorrectAnswer && isUserAnswer;
    const isUserAnswerWrong = isUserAnswer && !isCorrectAnswer;

    if (isCorrectAndUserAnswer) {
      return "bg-blue-900 text-white border-blue-900";
    } else if (isCorrectAnswer) {
      return "bg-green-500 text-white border-green-500";
    } else if (isUserAnswerWrong) {
      return "bg-red-500 text-white border-red-500";
    }
    return "border-gray-300";
  };

  // Handle browser back button
  useEffect(() => {
    const handlePopState = () => {
      router.push("/unit");
    };

    window.addEventListener("popstate", handlePopState);
    return () => window.removeEventListener("popstate", handlePopState);
  }, [router]);

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container mx-auto px-4 py-8 max-w-4xl">
        {/* Header */}
        <div className="mb-8">
          <button
            onClick={() => router.push("/unit")}
            className="flex items-center text-gray-700 hover:text-gray-900 transition-colors mb-6"
          >
            <ArrowLeft size={30} />
          </button>
        </div>

        {/* Main Content */}
        <div className="space-y-8">
          {/* Score Message */}
          <h1 className="text-3xl font-bold text-blue-900 text-center mb-6">
            {getScoreMessage(resultSheet.score)}
          </h1>

          {/* Score Card */}
          <div className="score-card">
            <p className="text-2xl font-medium mb-4">Score:</p>
            <div className="flex items-center justify-center gap-4">
              <div className="w-15 h-15 bg-blue-900 rounded-full flex items-center justify-center">
                <div className="w-6 h-6 bg-white rounded-full"></div>
              </div>
              <span className="text-6xl font-bold text-blue-900">
                {resultSheet.score}
              </span>
            </div>
          </div>

          {/* Solutions Section */}
          <div className="mt-10">
            <h2 className="text-3xl font-bold text-blue-900 mb-6">Solutions</h2>

            <div className="space-y-6">
              {resultSheet.questions.map((question, idx) => (
                <div key={idx} className="question-card">
                  {/* Question Header */}
                  <div className="flex justify-between items-start mb-4">
                    <h3 className="text-xl font-medium flex-1">
                      {idx + 1}. {question.question}
                    </h3>
                    <span
                      className={`status-badge ${getStatusColor(question)}`}
                    >
                      {getStatusText(question)}
                    </span>
                  </div>

                  {/* Options */}
                  <div className="space-y-3 mb-6">
                    {Object.entries(question.options).map(([key, option]) => (
                      <div key={key} className="flex items-center gap-4">
                        <span
                          className={`option-letter ${getOptionClassName(
                            key,
                            question
                          )}`}
                        >
                          {key.toUpperCase()}
                        </span>
                        <span className="text-lg">{option}</span>
                      </div>
                    ))}
                  </div>

                  {/* Solution Divider */}
                  <div className="solution-divider"></div>

                  {/* Solution */}
                  <div>
                    <h4 className="text-xl font-semibold text-gray-500 mb-3">
                      Solution:
                    </h4>
                    <p className="text-lg leading-relaxed text-gray-800">
                      {question.solution}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Bottom Button */}
        <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4">
          <div className="container mx-auto max-w-4xl">
            <button
              onClick={() => router.push("/unit")}
              className="w-full bg-blue-900 text-white py-4 px-6 rounded-lg font-bold text-xl hover:bg-blue-800 transition-colors"
            >
              Next
            </button>
          </div>
        </div>

        {/* Spacer for fixed button */}
        <div className="h-24"></div>
      </div>

      <style jsx>{`
        .score-card {
          height: 170px;
          width: 100%;
          border: 2px solid #c1dcff;
          border-radius: 25px;
          padding: 24px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          gap: 12px;
          background: white;
        }

        .question-card {
          border: 2px solid #abd0ff;
          padding: 24px;
          border-radius: 20px;
          background: white;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .status-badge {
          padding: 6px 16px;
          border-radius: 12px;
          color: white;
          font-weight: bold;
          font-size: 14px;
          white-space: nowrap;
        }

        .option-letter {
          min-width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          border: 1px solid;
          font-size: 14px;
          font-weight: 500;
        }

        .solution-divider {
          width: 100%;
          height: 1px;
          border-top: 1px dashed #000;
          margin: 20px 0;
        }

        @media (max-width: 768px) {
          .score-card {
            height: 150px;
            padding: 20px;
          }

          .question-card {
            padding: 20px;
            border-radius: 16px;
          }

          .status-badge {
            font-size: 12px;
            padding: 4px 12px;
          }

          .option-letter {
            min-width: 28px;
            height: 28px;
            font-size: 12px;
          }
        }

        @media (max-width: 640px) {
          .container {
            padding-left: 16px;
            padding-right: 16px;
          }
        }
      `}</style>
    </div>
  );
};

export default ResultsPage;
