import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import "./CourseTable.css";
import { fetchCourses } from "../api";

const CourseTable = () => {
  const { state } = useLocation();
  const [courses, setCourses] = useState(state?.courses || []);
  const [loading, setLoading] = useState(!state?.courses);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchAllCourses = async () => {
      if (!state?.courses) {
        try {
          const fetchedCourses = await fetchCourses(); // Fetch courses from API
          setCourses(fetchedCourses);
        } catch (error) {
          console.error("Failed to fetch courses:", error);
        } finally {
          setLoading(false);
        }
      }
    };

    fetchAllCourses();
  }, [state?.courses]);

  useEffect(() => {
    if (state?.updatedCourse) {
      setCourses((prevCourses) =>
        prevCourses.map((course) =>
          course.courseId === state.updatedCourse.courseId
            ? { ...course, status: "Submitted" } // Update the status for the specific course
            : course
        )
      );
    }
  }, [state?.updatedCourse]);
  


  if (loading) {
    return <div>Loading...</div>;
  }

  const handleRowClick = (course) => {
    navigate(`/course-form/${course.courseId}`, { state: { course } });
  };

  return (
    <table className="course-table">
      <thead>
        <tr>
          <th>CourseID</th>
          <th>Course Name</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody>
        {courses.length > 0 ? (
          courses.map((course) => (
            <tr key={course.courseId} onClick={() => handleRowClick(course)}>
              <td>{course.courseId}</td>
              <td>{course.name}</td>
              <td>{course.status}</td>
            </tr>
          ))
        ) : (
          <tr>
            <td colSpan="3">No courses available</td>
          </tr>
        )}
      </tbody>
    </table>
  );
};

export default CourseTable;
