import React, { useState, useEffect } from "react";
import axios from "axios";
import Navbar from "./Navbar";
import Footer from "./Footer";


const DepartmentConsolidated = () => {
  const [searchQuery, setSearchQuery] = useState("");
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const tablesPerPage = 5;
  const [expandedDepartment, setExpandedDepartment] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(
          "http://localhost:8080/api/table/department-consolidated",
          { withCredentials: true }
        );
        setData(response.data);
        setLoading(false);
      } catch (error) {
        console.error("Error fetching table data:", error);
        setLoading(false);
      }
    };

    fetchData();
  }, []);

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

  // Filter departments based on search query
  const filteredDepartments = data.filter((department) =>
    department.department.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const totalPages = Math.ceil(filteredDepartments.length / tablesPerPage);
  const indexOfLastTable = currentPage * tablesPerPage;
  const indexOfFirstTable = indexOfLastTable - tablesPerPage;
  const currentDepartments = filteredDepartments.slice(
    indexOfFirstTable,
    indexOfLastTable
  );

  const handleNextPage = () => {
    if (currentPage < totalPages) setCurrentPage((prevPage) => prevPage + 1);
  };

  const handlePrevPage = () => {
    if (currentPage > 1) setCurrentPage((prevPage) => prevPage - 1);
  };

  return (
    <div style={{
      display:"flex",
      flexDirection:"column",
      minHeight: "100vh"
    }}>
      <Navbar />
      <div style={{
        flexGrow: 1
      }}>
        <h1
          style={{
            textAlign: "center",
            background: "#003366",
            color: "white",
            padding: "20px 0",
            fontSize: "24px",
          }}
        >
          Department-wise Course Tables
        </h1>

        <div style={{ padding: "10px", marginBottom: "30px" }}>
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search for a department..."
            style={{
              width: "100%",
              padding: "10px",
              borderRadius: "5px",
              border: "1px solid #ccc",
              fontSize: "16px",
            }}
          />
        </div>

        <div
          style={{
            maxHeight: "70vh",
            overflowY: "auto",
            border: "1px solid #ccc",
            padding: "10px",
            borderRadius: "5px",
            backgroundColor: "#f9f9f9",
          }}
        >
          {currentDepartments.map((department, index) => (
            <div key={index} style={{ marginBottom: "20px" }}>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  cursor: "pointer",
                  backgroundColor: "#ffffff",
                  color: "black",
                  padding: "10px",
                  borderRadius: "5px",
                }}
                onClick={() =>
                  setExpandedDepartment(
                    expandedDepartment === department.department
                      ? null
                      : department.department
                  )
                }
              >
                <h2 style={{ margin: 0 }}>{department.department}</h2>
              </div>

              {expandedDepartment === department.department && (
                <div>
                  {department.courses.map((course, courseIndex) => (
                    <div key={courseIndex} style={{ marginTop: "20px" }}>
                      <h3 style={{ marginBottom: "10px" }}>
                        {course.courseName} ({course.courseCode})
                      </h3>
                      <table
                        border="1"
                        style={{
                          width: "100%",
                          textAlign: "left",
                          marginBottom: "20px",
                        }}
                      >
                        <thead>
                          <tr>
                            <th>Semester</th>
                            <th>Course Code</th>
                            <th>Course Name</th>
                            <th>Exam Type</th>
                            <th>Year</th>
                            <th>Oral/Practical</th>
                            <th>Assessment</th>
                            <th>Reassessment</th>
                            <th>Paper Setting</th>
                            <th>Moderation</th>
                            <th>PwD Paper Setting</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr>
                            <td>{course.semester}</td>
                            <td>{course.courseCode}</td>
                            <td>{course.courseName}</td>
                            <td>{course.examType}</td>
                            <td>{course.year}</td>
                            <td>
                              {course.oralPracticalTeachers.length > 0 ? (
                                <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                  {course.oralPracticalTeachers.map(
                                    (teacher, idx) => (
                                      <li key={idx}>{teacher}</li>
                                    )
                                  )}
                                </ul>
                              ) : (
                                "N/A"
                              )}
                            </td>
                            <td>
                              {course.assessmentTeachers.length > 0 ? (
                                <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                  {course.assessmentTeachers.map(
                                    (teacher, idx) => (
                                      <li key={idx}>{teacher}</li>
                                    )
                                  )}
                                </ul>
                              ) : (
                                "N/A"
                              )}
                            </td>
                            <td>
                              {course.reassessmentTeachers.length > 0 ? (
                                <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                  {course.reassessmentTeachers.map(
                                    (teacher, idx) => (
                                      <li key={idx}>{teacher}</li>
                                    )
                                  )}
                                </ul>
                              ) : (
                                "N/A"
                              )}
                            </td>
                            <td>
                              {course.paperSettingTeachers.length > 0 ? (
                                <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                  {course.paperSettingTeachers.map(
                                    (teacher, idx) => (
                                      <li key={idx}>{teacher}</li>
                                    )
                                  )}
                                </ul>
                              ) : (
                                "N/A"
                              )}
                            </td>
                            <td>
                              {course.moderationTeachers.length > 0 ? (
                                <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                  {course.moderationTeachers.map(
                                    (teacher, idx) => (
                                      <li key={idx}>{teacher}</li>
                                    )
                                  )}
                                </ul>
                              ) : (
                                "N/A"
                              )}
                            </td>
                            <td>
                              {course.pwdPaperSettingTeachers.length > 0 ? (
                                <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                  {course.pwdPaperSettingTeachers.map(
                                    (teacher, idx) => (
                                      <li key={idx}>{teacher}</li>
                                    )
                                  )}
                                </ul>
                              ) : (
                                "N/A"
                              )}
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>

        {/* Pagination controls */}
        <div style={{ textAlign: "center", marginTop: "20px" }}>
          <button
            onClick={handlePrevPage}
            disabled={currentPage === 1}
            style={{
              padding: "10px 15px",
              marginRight: "10px",
              backgroundColor: currentPage === 1 ? "#ccc" : "#007bff",
              color: "white",
              borderRadius: "5px",
              border: "none",
            }}
          >
            Previous
          </button>
          <span>
            Page {currentPage} of {totalPages}
          </span>
          <button
            onClick={handleNextPage}
            disabled={currentPage === totalPages}
            style={{
              padding: "10px 15px",
              marginLeft: "10px",
              backgroundColor: currentPage === totalPages ? "#ccc" : "#007bff",
              color: "white",
              borderRadius: "5px",
              border: "none",
            }}
          >
            Next
          </button>
        </div>
      </div>
      <Footer/>
    </div>
  );
};

export default DepartmentConsolidated;