import { useEffect, useState } from "react";
import { getExam } from "@/_lib/api/exams";
import { ExamType } from "@/_types/Types";

export const useExam = (examId: string | null) => {
  const [exam, setExam] = useState<ExamType | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<null | unknown>(null);

  useEffect(() => {
    if (!examId) {
      setExam(null);
      return;
    }

    const fetchData = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await getExam(examId);
        setExam(response.data);
      } catch (err: unknown) {
        setError(err);
        setExam(null);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [examId]);

  return { exam, loading, error };
};
