import React, { useState, useEffect } from "react";
import axios from "axios";
import { jsPDF } from "jspdf";
import autoTable from "jspdf-autotable";
import Navbar from "./Navbar";
import { toast } from "react-toastify";
import { sendEmail } from "../api";
import Footer from "./Footer";


const CourseConsolidated = () => {
  const [searchQuery, setSearchQuery] = useState(""); // State for the search input
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const tablesPerPage = 5;
  const [expandedCourse, setExpandedCourse] = useState(null);
  

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(
          "http://localhost:8080/api/table/course-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>;
  }

  // Extract unique courses by courseCode
  const filteredCourses = [
    ...new Set(data.map((row) => row.courseCode)),
  ].filter((courseCode) => {
    const courseName = data.find(
      (row) => row.courseCode === courseCode
    )?.courseName;
    return (
      courseName && courseName.toLowerCase().includes(searchQuery.toLowerCase())
    );
  });

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

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

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

  const fetchFacultyEmail = async (facultyId) => {
    try {
      const response = await axios.get(
        `http://localhost:8080/api/faculty/${facultyId}`,
        { withCredentials: true }
      );
      return response.data.email; // Assuming API returns { email: "faculty@example.com" }
    } catch (error) {
      console.error(`Error fetching email for ${facultyId}:`, error);
      return "N/A"; // Return "N/A" if email is not found
    }
  };

  // const generateAppointmentPDFs = async (courseData, courseName) => {
  //   const maroon = [128, 0, 0];
  //   const roles = [
  //     { key: "oralPracticalTeachers", role: "Oral/Practical Teacher" },
  //     { key: "assessmentTeachers", role: "Assessment Teacher" },
  //     { key: "reassessmentTeachers", role: "Reassessment Teacher" },
  //     { key: "paperSettingTeachers", role: "Paper Setter" },
  //     { key: "moderationTeachers", role: "Moderator" },
  //     { key: "pwdPaperSettingTeachers", role: "PwD Paper Setter" },
  //   ];
  
  //   // ✅ NEW: Group appointments by Faculty ID
  //   const facultyMap = {};
  
  //   for (const { key, role } of roles) {
  //     if (!courseData[key] || courseData[key].length === 0) continue;
  
  //     for (const teacher of courseData[key]) {
  //       if (!facultyMap[teacher.facultyId]) {
  //         facultyMap[teacher.facultyId] = {
  //           facultyName: teacher.facultyName,
  //           email: await fetchFacultyEmail(teacher.facultyId),
  //           appointments: [],
  //         };
  //       }
  //       facultyMap[teacher.facultyId].appointments.push({
  //         role,
  //         teacher,
  //       });
  //     }
  //   }
  
  //   // ✅ NEW: For each Faculty, generate PDFs & send one email
  //   for (const facultyId in facultyMap) {
  //     const faculty = facultyMap[facultyId];
  //     const pdfBlobs = [];
  
  //     for (const appointment of faculty.appointments) {
  //       const { role } = appointment;
  
  //       const doc = new jsPDF();
  
  //       // Add Logo and Title (your original PDF content)
  //       const logoUrl = "/logo.png";
  //       const loadImage = async (url) => {
  //         const response = await fetch(url);
  //         const blob = await response.blob();
  //         return new Promise((resolve, reject) => {
  //           const reader = new FileReader();
  //           reader.onload = () => resolve(reader.result);
  //           reader.onerror = (error) => reject(error);
  //           reader.readAsDataURL(blob);
  //         });
  //       };
  
  //       try {
  //         const logoBase64 = await loadImage(logoUrl);
  //         doc.addImage(logoBase64, "PNG", 10, 10, 40, 40);
  //       } catch (error) {
  //         console.error("Failed to load logo:", error);
  //       }
  
  //       doc.setFont("times", "normal");
  //       doc.text(`Date: ${new Date().toLocaleDateString()}`, 150, 20);
  //       doc.text("CONFIDENTIAL", 10, 60);
  //       doc.text(`LETTER OF APPOINTMENT AS ${role.toUpperCase()}`, 105, 70, { align: "center" });
  
  //       autoTable(doc, {
  //         head: [["Name", "Affiliation", "Appointment Role", "Email"]],
  //         body: [[faculty.facultyName, "K. J. Somaiya School of Engineering", role, faculty.email]],
  //         startY: 80,
  //         theme: "grid",
  //         headStyles: { fillColor: maroon, textColor: [255, 255, 255] },
  //       });
  
  //       autoTable(doc, {
  //         body: [
  //           ["Programme:", courseData.courseName],
  //           ["Exam Category:", "Regular Examination"],
  //           ["Exam Type:", courseData.examType],
  //           ["Exam Season:", "Second Half - Winter Examination 2023"],
  //           ["Year:", courseData.year],
  //           ["Semester:", courseData.semester],
  //           ["Course Name:", courseName],
  //           ["Course Code:", courseData.courseCode],
  //         ],
  //         startY: doc.previousAutoTable.finalY + 10,
  //         theme: "grid",
  //       });
  
  //       const pdfBlob = doc.output("blob");
  //       pdfBlobs.push({ blob: pdfBlob, filename: `${courseName}-${role}.pdf` });
  //     }
  
  //     // ✅ NEW: Send ONE email with ALL PDFs to the Faculty
  //     try {
  //       const formData = new FormData();
  
  //       pdfBlobs.forEach(({ blob, filename }) => {
  //         formData.append("pdfFiles", blob, filename); // note 'pdfFiles' is plural
  //       });
  
  //       formData.append("recipientEmail", faculty.email);
  //       formData.append("facultyName", faculty.facultyName);
  //       formData.append("courseName", courseName);
  
  //       const emailResponse = await sendEmail(formData, "bulk-pdf");
  //       toast.success(`✅ Email sent successfully to ${faculty.email}`);
  //       console.log("Response:", emailResponse);
  //     } catch (error) {
  //       toast.error(`❌ Error sending email to ${faculty.email}: ${error.message}`);
  //       console.error(error);
  //     }
  //   }
  // };
  
  // const generateAppointmentPDFs = async (courseData, courseName) => {
  //   const maroon = [128, 0, 0];
  //   const roles = [
  //     { key: "oralPracticalTeachers", role: "Oral/Practical Teacher" },
  //     { key: "assessmentTeachers", role: "Assessment Teacher" },
  //     { key: "reassessmentTeachers", role: "Reassessment Teacher" },
  //     { key: "paperSettingTeachers", role: "Paper Setter" },
  //     { key: "moderationTeachers", role: "Moderator" },
  //     { key: "pwdPaperSettingTeachers", role: "PwD Paper Setter" },
  //   ];
  
  //   // Group appointments by Faculty ID and by role
  //   const facultyMap = {};
  //   const roleFaculties = {}; // Store faculties by role
  
  //   for (const { key, role } of roles) {
  //     if (!courseData[key] || courseData[key].length === 0) continue;
  
  //     for (const teacher of courseData[key]) {
  //       if (!facultyMap[teacher.facultyId]) {
  //         facultyMap[teacher.facultyId] = {
  //           facultyName: teacher.facultyName,
  //           email: await fetchFacultyEmail(teacher.facultyId),
  //           appointments: [],
  //         };
  //       }
  //       facultyMap[teacher.facultyId].appointments.push({ role, teacher });
  
  //       // Add faculty to the role-specific list
  //       if (!roleFaculties[role]) roleFaculties[role] = [];
  //       roleFaculties[role].push(teacher.facultyName);
  //     }
  //   }
  
  //   // Generate PDF for each faculty
  //   for (const facultyId in facultyMap) {
  //     const faculty = facultyMap[facultyId];
  //     const pdfBlobs = [];
  
  //     for (const appointment of faculty.appointments) {
  //       const { role } = appointment;
  
  //       const doc = new jsPDF();
  //       const logoUrl = "/logo.png";
  //       const loadImage = async (url) => {
  //         const response = await fetch(url);
  //         const blob = await response.blob();
  //         return new Promise((resolve, reject) => {
  //           const reader = new FileReader();
  //           reader.onload = () => resolve(reader.result);
  //           reader.onerror = (error) => reject(error);
  //           reader.readAsDataURL(blob);
  //         });
  //       };
  
  //       try {
  //         const logoBase64 = await loadImage(logoUrl);
  //         doc.addImage(logoBase64, "PNG", 10, 10, 40, 40);
  //       } catch (error) {
  //         console.error("Failed to load logo:", error);
  //       }
  
  //       doc.setFont("times", "normal");
  //       doc.text(`Date: ${new Date().toLocaleDateString()}`, 150, 20);
  //       doc.text("CONFIDENTIAL", 10, 60);
  //       doc.text(`LETTER OF APPOINTMENT AS ${role.toUpperCase()}`, 105, 70, { align: "center" });
  
  //       // Include other faculties performing the same role
  //       const otherFaculties = roleFaculties[role].filter(
  //         (name) => name !== faculty.facultyName
  //       );
  //       doc.text(
  //         `Other faculties performing the same role: ${otherFaculties.join(", ")}`,
  //         10,
  //         90
  //       );
  
  //       autoTable(doc, {
  //         head: [["Name", "Affiliation", "Appointment Role", "Email"]],
  //         body: [[faculty.facultyName, "K. J. Somaiya School of Engineering", role, faculty.email]],
  //         startY: 100,
  //         theme: "grid",
  //         headStyles: { fillColor: maroon, textColor: [255, 255, 255] },
  //       });
  
  //       autoTable(doc, {
  //         body: [
  //           ["Programme:", courseData.courseName],
  //           ["Exam Category:", "Regular Examination"],
  //           ["Exam Type:", courseData.examType],
  //           ["Exam Season:", "Second Half - Winter Examination 2023"],
  //           ["Year:", courseData.year],
  //           ["Semester:", courseData.semester],
  //           ["Course Name:", courseName],
  //           ["Course Code:", courseData.courseCode],
  //         ],
  //         startY: doc.previousAutoTable.finalY + 10,
  //         theme: "grid",
  //       });
  
  //       const pdfBlob = doc.output("blob");
  //       pdfBlobs.push({ blob: pdfBlob, filename: `${courseName}-${role}.pdf` });
  //     }
  
  //     // Send ONE email with ALL PDFs to the Faculty
  //     try {
  //       const formData = new FormData();
  //       pdfBlobs.forEach(({ blob, filename }) => {
  //         formData.append("pdfFiles", blob, filename);
  //       });
  
  //       formData.append("recipientEmail", faculty.email);
  //       formData.append("facultyName", faculty.facultyName);
  //       formData.append("courseName", courseName);
  
  //       const emailResponse = await sendEmail(formData, "bulk-pdf");
  //       toast.success(`✅ Email sent successfully to ${faculty.email}`);
  //       console.log("Response:", emailResponse);
  //     } catch (error) {
  //       toast.error(`❌ Error sending email to ${faculty.email}: ${error.message}`);
  //       console.error(error);
  //     }
  //   }
  // };
  
  const generateAppointmentPDFs = async (courseData, courseName) => {
    const maroon = [128, 0, 0];
    const roles = [
      { key: "oralPracticalTeachers", role: "Oral/Practical Teacher" },
      { key: "assessmentTeachers", role: "Assessment Teacher" },
      { key: "reassessmentTeachers", role: "Reassessment Teacher" },
      { key: "paperSettingTeachers", role: "Paper Setter" },
      { key: "moderationTeachers", role: "Moderator" },
      { key: "pwdPaperSettingTeachers", role: "PwD Paper Setter" },
    ];
  
    // Group appointments by Faculty ID and by role
    const facultyMap = {};
    const roleFaculties = {}; // Store faculty IDs by role
  
    for (const { key, role } of roles) {
      if (!courseData[key] || courseData[key].length === 0) continue;
  
      for (const teacher of courseData[key]) {
        if (!facultyMap[teacher.facultyId]) {
          facultyMap[teacher.facultyId] = {
            facultyName: teacher.facultyName,
            email: await fetchFacultyEmail(teacher.facultyId),
            appointments: [],
          };
        }
        facultyMap[teacher.facultyId].appointments.push({ role, teacher });
  
        // Add facultyId to the role-specific list
        if (!roleFaculties[role]) roleFaculties[role] = [];
        roleFaculties[role].push(teacher.facultyId); // Store facultyId instead of facultyName
      }
    }
  
    // Generate PDF for each faculty
    for (const facultyId in facultyMap) {
      const faculty = facultyMap[facultyId];
      const pdfBlobs = [];
  
      for (const appointment of faculty.appointments) {
        const { role } = appointment;
  
        const doc = new jsPDF();
        const logoUrl = "/logo.png";
        const loadImage = async (url) => {
          const response = await fetch(url);
          const blob = await response.blob();
          return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result);
            reader.onerror = (error) => reject(error);
            reader.readAsDataURL(blob);
          });
        };
  
        try {
          const logoBase64 = await loadImage(logoUrl);
          doc.addImage(logoBase64, "PNG", 10, 10, 40, 40);
        } catch (error) {
          console.error("Failed to load logo:", error);
        }
  
        doc.setFont("times", "normal");
        doc.text(`Date: ${new Date().toLocaleDateString()}`, 150, 20);
        doc.text("CONFIDENTIAL", 10, 60);
        doc.text(`LETTER OF APPOINTMENT AS ${role.toUpperCase()}`, 105, 70, { align: "center" });
  
        // Include all faculties performing the same role inside the table
        const roleFacultyDetails = roleFaculties[role].map((facultyId) => {
          const facultyDetail = facultyMap[facultyId]; // Access by facultyId
          return [
            facultyDetail.facultyName,
            "K. J. Somaiya School of Engineering",
            role,
            facultyDetail.email,
          ];
        });
  
        autoTable(doc, {
          head: [["Name", "Affiliation", "Appointment Role", "Email"]],
          body: roleFacultyDetails, // Mapping through all faculties in the role
          startY: 100,
          theme: "grid",
          headStyles: { fillColor: maroon, textColor: [255, 255, 255] },
        });
  
        autoTable(doc, {
          body: [
            ["Programme:", courseData.courseName],
            ["Exam Category:", "Regular Examination"],
            ["Exam Type:", courseData.examType],
            ["Exam Season:", "Second Half - Winter Examination 2023"],
            ["Year:", courseData.year],
            ["Semester:", courseData.semester],
            ["Course Name:", courseName],
            ["Course Code:", courseData.courseCode],
          ],
          startY: doc.previousAutoTable.finalY + 10,
          theme: "grid",
        });
  
        const pdfBlob = doc.output("blob");
        pdfBlobs.push({ blob: pdfBlob, filename: `${courseName}-${role}.pdf` });
      }
  
      // Send ONE email with ALL PDFs to the Faculty
      try {
        const formData = new FormData();
        pdfBlobs.forEach(({ blob, filename }) => {
          formData.append("pdfFiles", blob, filename);
        });
  
        formData.append("recipientEmail", faculty.email);
        formData.append("facultyName", faculty.facultyName);
        formData.append("courseName", courseName);
  
        const emailResponse = await sendEmail(formData, "bulk-pdf");
        toast.success(`✅ Email sent successfully to ${faculty.email}`);
        console.log("Response:", emailResponse);
      } catch (error) {
        toast.error(`❌ Error sending email to ${faculty.email}: ${error.message}`);
        console.error(error);
      }
    }
  };
  
  
  

  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",
          }}
        >
          Course Tables with Download Options
        </h1>

        <div style={{ padding: "10px", marginBottom: "30px" }}>
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search for a course..."
            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",
            fontSize: "160px",
          }}
        >
          {currentCourses.map((courseCode, index) => {
            const courseData = data.filter(
              (row) => row.courseCode === courseCode
            );
            console.log(courseData);
            const courseName = courseData[0]?.courseName; // Get course name from first item
            return (
              <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={() =>
                    setExpandedCourse(
                      expandedCourse === courseCode ? null : courseCode
                    )
                  }
                >
                  <h2 style={{ margin: 0 }}>{courseName}'s Table</h2>
                  <button
                    onClick={() =>
                      generateAppointmentPDFs(courseData[0], courseName)
                    }
                    className="btn btn-primary"
                    style={{
                      padding: "10px 15px",
                      backgroundColor: "#007bff",
                      color: "white",
                      textDecoration: "none",
                      borderRadius: "5px",
                    }}
                  >
                    Download
                  </button>
                </div>

                {expandedCourse === courseCode && (
                  <table
                    border="1"
                    style={{
                      width: "100%",
                      textAlign: "left",
                      marginTop: "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>
                      {courseData.map((row, idx) => (
                        <tr key={idx}>
                          <td>{row.semester}</td>
                          <td>{row.courseCode}</td>
                          <td>{row.courseName}</td>
                          <td>{row.examType}</td>
                          <td>{row.year}</td>
                          <td>
                            {row.oralPracticalTeachers &&
                            row.oralPracticalTeachers.length > 0 ? (
                              <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                {row.oralPracticalTeachers.map(
                                  (teacher, idx) => (
                                    <li key={idx}>{teacher.facultyName}</li>
                                  )
                                )}
                              </ul>
                            ) : (
                              "N/A"
                            )}
                          </td>
                          <td>
                            {row.assessmentTeachers &&
                            row.assessmentTeachers.length > 0 ? (
                              <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                {row.assessmentTeachers.map((teacher, idx) => (
                                  <li key={idx}>{teacher.facultyName}</li>
                                ))}
                              </ul>
                            ) : (
                              "N/A"
                            )}
                          </td>
                          <td>
                            {row.reassessmentTeachers &&
                            row.reassessmentTeachers.length > 0 ? (
                              <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                {row.reassessmentTeachers.map(
                                  (teacher, idx) => (
                                    <li key={idx}>{teacher.facultyName}</li>
                                  )
                                )}
                              </ul>
                            ) : (
                              "N/A"
                            )}
                          </td>
                          <td>
                            {row.paperSettingTeachers &&
                            row.paperSettingTeachers.length > 0 ? (
                              <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                {row.paperSettingTeachers.map(
                                  (teacher, idx) => (
                                    <li key={idx}>{teacher.facultyName}</li>
                                  )
                                )}
                              </ul>
                            ) : (
                              "N/A"
                            )}
                          </td>
                          <td>
                            {row.moderationTeachers &&
                            row.moderationTeachers.length > 0 ? (
                              <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                {row.moderationTeachers.map((teacher, idx) => (
                                  <li key={idx}>{teacher.facultyName}</li>
                                ))}
                              </ul>
                            ) : (
                              "N/A"
                            )}
                          </td>
                          <td>
                            {row.pwdPaperSettingTeachers &&
                            row.pwdPaperSettingTeachers.length > 0 ? (
                              <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                {row.pwdPaperSettingTeachers.map(
                                  (teacher, idx) => (
                                    <li key={idx}>{teacher.facultyName}</li>
                                  )
                                )}
                              </ul>
                            ) : (
                              "N/A"
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
              </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 CourseConsolidated;
