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

const PanelConsolidated = () => {
    const [faculty, setFaculty] = useState([]);
    const [courses, setCourses] = useState([]);
    const [search, setSearch] = useState("");
    const [expandedCourse, setExpandedCourse] = useState(null);

    useEffect(() => {
        axios.get("http://localhost:8080/api/faculty")
            .then((response) => {
                setFaculty(response.data);
            })
            .catch((error) => {
                console.error("Error fetching faculty data:", error);
            });

        axios.get("http://localhost:8080/api/courses")
            .then((response) => {
                setCourses(response.data);
            })
            .catch((error) => {
                console.error("Error fetching course data:", error);
            });
    }, []);

    const groupedCourses = {};
    courses.forEach((course) => {
        if (!groupedCourses[course.semester]) {
            groupedCourses[course.semester] = [];
        }
        groupedCourses[course.semester].push(course);
    });

    const sortedSemesters = Object.keys(groupedCourses).sort((a, b) => a - b);

    const courseFacultyMap = {};
    faculty.forEach((fac) => {
        fac.courses.forEach((courseId) => {
            if (!courseFacultyMap[courseId]) {
                courseFacultyMap[courseId] = [];
            }
            courseFacultyMap[courseId].push({
                facultyId: fac.facultyId,
                name: fac.name,
                department: fac.department,
                email: fac.email,
            });
        });
    });

    const toggleCourse = (courseId) => {
        setExpandedCourse(expandedCourse === courseId ? null : courseId);
    };

    return (
        <div style={{
            display:"flex",
            flexDirection:"column",
            minHeight: "100vh"
          }}>
            <Navbar />
            <div style={{ padding: "24px", backgroundColor: "#f7f7f7", minHeight: "100vh", flexGrow:1 }}>
                <h2 style={{ fontSize: "24px", fontWeight: "bold", marginBottom: "16px" }}>Faculty Expertise</h2>

                <input
                    type="text"
                    placeholder="Search by Course Name"
                    style={{ marginBottom: "16px", padding: "8px", border: "1px solid #ccc", borderRadius: "4px", width: "100%", maxWidth: "300px" }}
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                />

                <div>
                    {sortedSemesters.map((semester) => (
                        <div key={semester}>
                            <h3
                                onClick={() => toggleCourse(courses.courseId)}
                                style={{ marginTop: "20px", fontSize: "20px", color: "#800000" }}
                            >
                                Semester {semester}
                            </h3>
                            {groupedCourses[semester].filter((course) => course.name.toLowerCase().includes(search.toLowerCase())).map((course) => (
                                <div key={course.courseId}>
                                    <div
                                        onClick={() => toggleCourse(course.courseId)}
                                        style={{
                                            cursor: "pointer",
                                            padding: "12px",
                                            backgroundColor: "#fff",
                                            marginBottom: "8px",
                                            border: "1px solid #ccc",
                                            borderRadius: "4px",
                                            fontWeight: "bold"
                                        }}
                                    >
                                        {course.name}
                                    </div>
                                    {expandedCourse === course.courseId && (
                                        <table style={{ width: "100%", borderCollapse: "collapse", backgroundColor: "#fff", border: "1px solid #ccc", marginBottom: "16px" }}>
                                            <thead>
                                                <tr style={{ backgroundColor: "#e5e5e5" }}>
                                                    <th style={{ border: "1px solid #ccc", padding: "8px" }}>Faculty ID</th>
                                                    <th style={{ border: "1px solid #ccc", padding: "8px" }}>Name</th>
                                                    <th style={{ border: "1px solid #ccc", padding: "8px" }}>Email</th>
                                                    <th style={{ border: "1px solid #ccc", padding: "8px" }}>Department</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {courseFacultyMap[course.courseId]?.map((faculty, index) => (
                                                    <tr key={index}>
                                                        <td style={{ border: "1px solid #ccc", padding: "8px" }}>{faculty.facultyId}</td>
                                                        <td style={{ border: "1px solid #ccc", padding: "8px" }}>{faculty.name}</td>
                                                        <td style={{ border: "1px solid #ccc", padding: "8px" }}>{faculty.email}</td>
                                                        <td style={{ border: "1px solid #ccc", padding: "8px" }}>{faculty.department}</td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    )}
                                </div>
                            ))}
                        </div>
                    ))}
                </div>
            </div>
            <Footer/>
        </div>
    );
};


export default PanelConsolidated;
