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

import FilterPage from "./FilterPage";
import Footer from "./Footer";

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

  useEffect(() => {
    const fetchData = async () => {
      try {
        const academicYear = state?.academicYear;
        const [fetchedAppointments, fetchedCourses] = await Promise.all([
          fetchAppointments(academicYear),
          state?.courses ? Promise.resolve(state.courses) : fetchCourses(),
        ]);
        setAppointments(fetchedAppointments);
        if (!state?.courses) setCourses(fetchedCourses);
      } catch (error) {
        console.error("Failed to fetch data:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [state?.courses, state?.academicYear]);

  const getStatus = (courseId) => {
    return appointments.some((appointment) => appointment.courseId === courseId)
      ? "Submitted"
      : "Not Submitted";
  };

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

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

  return (
    <div style={{
      display:"flex",
      flexDirection:"column",
      minHeight: "100vh"
    }}>
     
      {/* Pass setCourses to FilterPage so it can update the course list */}
        <div style={{flexGrow:1}}>
          <FilterPage setCourses={setCourses} />
          <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>{getStatus(course.courseId)}</td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan="3">No courses available</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      <Footer/>
    </div>
  );
};

export default CourseTable;
