"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useState } from "react";
import { ArrowLeft, HelpCircle, Clock, XCircle } from "lucide-react";
import DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL } from "@/lib/auth";
import { useExam } from "@/context/ExamContext";
import { Exam } from "@/types/exam";

interface Metadata {
  metadata: {
    quantity: number;
    type: string;
    duration: number;
    marking: string;
  };
}

function PretestPageContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [examData, setExamData] = useState<Exam>();
  const { startExam, setCurrentExam } = useExam();

  // Get params from URL search params
  const id = searchParams.get("id") || "";
  const title = searchParams.get("title") || "";
  const rating = searchParams.get("rating") || "";

  const [metadata, setMetadata] = useState<Metadata | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>();

  useEffect(() => {
    async function fetchQuestions() {
      if (!id) return;

      try {
        setLoading(true);
        const questionResponse = await fetch(`${API_URL}/mock/${id}`, {
          method: "GET",
        });
        if (!questionResponse.ok) {
          throw new Error("Failed to fetch questions");
        }
        const data = await questionResponse.json();
        const fetchedMetadata: Metadata = data;

        setExamData(data);
        setMetadata(fetchedMetadata);
      } catch (error) {
        console.error(error);
        setError(error instanceof Error ? error.message : "An error occurred");
      } finally {
        setLoading(false);
      }
    }
    if (id) {
      fetchQuestions();
    }
  }, [id]);

  if (error) {
    return (
      <BackgroundWrapper>
        <div className="min-h-screen">
          <div className="mx-10 mt-10">
            <button onClick={() => router.push("/unit")} className="mb-4">
              <ArrowLeft size={30} color="black" />
            </button>
            <DestructibleAlert text={error} extraStyles="" />
          </div>
        </div>
      </BackgroundWrapper>
    );
  }

  function handleStartExam() {
    if (!examData) return;

    setCurrentExam(examData);
    startExam(examData);
    router.push(`/exam/${id}?time=${metadata?.metadata.duration}`);
  }
  return (
    <BackgroundWrapper>
      <div className="min-h-screen flex flex-col justify-between">
        <div className="flex-1 overflow-y-auto mb-20">
          {metadata ? (
            <div className="mx-10 mt-10 gap-6 pb-6 space-y-6">
              <button onClick={() => router.back()}>
                <ArrowLeft size={30} color="black" />
              </button>

              <h1 className="text-4xl font-semibold text-[#113768]">{title}</h1>

              <p className="text-xl font-medium text-[#113768]">
                Rating: {rating} / 10
              </p>

              <div className="border-[1.5px] border-[#226DCE]/30 rounded-[25px] gap-8 py-7 px-5 space-y-8">
                <div className="flex gap-5 items-center">
                  <HelpCircle size={40} color="#113768" />
                  <div className="space-y-2">
                    <p className="font-bold text-4xl text-[#113768]">
                      {metadata.metadata.quantity}
                    </p>
                    <p className="font-normal text-lg">
                      {metadata.metadata.type}
                    </p>
                  </div>
                </div>

                <div className="flex gap-5 items-center">
                  <Clock size={40} color="#113768" />
                  <div className="space-y-2">
                    <p className="font-bold text-4xl text-[#113768]">
                      {metadata.metadata.duration} mins
                    </p>
                    <p className="font-normal text-lg">Time Taken</p>
                  </div>
                </div>

                <div className="flex gap-5 items-center">
                  <XCircle size={40} color="#113768" />
                  <div className="space-y-2">
                    <p className="font-bold text-4xl text-[#113768]">
                      {metadata.metadata.marking}
                    </p>
                    <p className="font-normal text-lg">
                      From each wrong answer
                    </p>
                  </div>
                </div>
              </div>

              <div className="border-[1.5px] border-[#226DCE]/30 rounded-[25px] gap-4 py-7 px-5 space-y-4">
                <h2 className="text-xl font-bold">Ready yourself!</h2>

                <div className="flex pr-4">
                  <span className="mx-4">•</span>
                  <p className="font-normal text-lg">
                    You must complete this test in one session - make sure your
                    internet connection is reliable.
                  </p>
                </div>

                <div className="flex pr-4">
                  <span className="mx-4">•</span>
                  <p className="font-normal text-lg">
                    There is negative marking for the wrong answer.
                  </p>
                </div>

                <div className="flex pr-4">
                  <span className="mx-4">•</span>
                  <p className="font-normal text-lg">
                    The more you answer correctly, the better chance you have of
                    winning a badge.
                  </p>
                </div>

                <div className="flex pr-4">
                  <span className="mx-4">•</span>
                  <p className="font-normal text-lg">
                    You can retake this test however many times you want. But,
                    you will earn points only once.
                  </p>
                </div>
              </div>
            </div>
          ) : (
            <div className="mt-60 flex flex-col items-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
              <p className="text-xl font-medium text-center">Loading...</p>
            </div>
          )}
        </div>

        <button
          onClick={async () => handleStartExam()}
          className="fixed bottom-0 w-full bg-[#113768] h-[78px] justify-center items-center flex text-white text-2xl font-bold"
        >
          Start Test
        </button>

        {/* <CustomBackHandler fallbackRoute="paper" /> */}
      </div>
    </BackgroundWrapper>
  );
}

export default function PretestPage() {
  return (
    <Suspense
      fallback={
        <BackgroundWrapper>
          <div className="min-h-screen">
            <div className="mx-10 mt-10 flex flex-col justify-center items-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-900 mb-4"></div>
              <p className="text-lg font-medium text-gray-900">Loading...</p>
            </div>
          </div>
        </BackgroundWrapper>
      }
    >
      <PretestPageContent />
    </Suspense>
  );
}
