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


const CourseConsolidated = () => {
  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"
        );
        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 uniqueCourses = [...new Set(data.map((row) => row.courseCode))];

  // Pagination
  const indexOfLastTable = currentPage * tablesPerPage;
  const indexOfFirstTable = indexOfLastTable - tablesPerPage;
  const currentCourses = uniqueCourses.slice(
    indexOfFirstTable,
    indexOfLastTable
  );

  const totalPages = Math.ceil(uniqueCourses.length / tablesPerPage);

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

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

  const generateAppointmentPDF = async (courseData, courseName) => {
    const doc = new jsPDF();
    const maroon = [128, 0, 0];
  
    // College Logo
    const logoUrl = "/logo.png"; // Ensure the logo is placed in the public folder
    const logoWidth = 40;
    const logoHeight = 40;
    const logoX = 10;
    const logoY = 10;
  
    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", logoX, logoY, logoWidth, logoHeight);
    } catch (error) {
      console.error("Failed to load logo:", error);
    }
  
    // Title Section
    doc.setFont("times", "normal");
    doc.setTextColor(0, 0, 0);
    doc.setFontSize(12);
    doc.text("Date: " + new Date().toLocaleDateString(), 150, 20);
    doc.setFontSize(14);
    doc.text("CONFIDENTIAL", 10, 60);
    doc.setFontSize(16);
    doc.text(
      "LETTER OF APPOINTMENT AS QUESTION PAPER SETTER",
      105,
      70,
      { align: "center" }
    );
  
    // Appointment Table
    const table1Data = [
      ...(courseData.oralPracticalTeachers?.map((teacher) => [
        teacher,
        "K. J. Somaiya School of Engineering",
        "Oral/Practical Teacher",
        "Contact Number",
      ]) || []),
      ...(courseData.assessmentTeachers?.map((teacher) => [
        teacher,
        "K. J. Somaiya School of Engineering",
        "Reassessment Teacher",
        "Contact Number",
      ]) || []),
      ...(courseData.reassessmentTeachers?.map((teacher) => [
        teacher,
        "K. J. Somaiya School of Engineering",
        "Reassessment Teacher",
        "Contact Number",
      ]) || []),
      ...(courseData.paperSettingTeachers?.map((teacher) => [
        teacher,
        "K. J. Somaiya School of Engineering",
        "Paper Setter",
        "Contact Number",
      ]) || []),
      ...(courseData.moderationTeachers?.map((teacher) => [
        teacher,
        "K. J. Somaiya School of Engineering",
        "Moderator",
        "Contact Number",
      ]) || []),
      ...(courseData.pwdPaperSettingTeachers?.map((teacher) => [
        teacher,
        "K. J. Somaiya School of Engineering",
        "PwD Paper Setter",
        "Contact Number",
      ]) || []),
    ];
  
    autoTable(doc, {
      head: [["Name", "Affiliation", "Appointment Role", "Email"]],
      body: table1Data,
      startY: 80,
      theme: "grid",
      headStyles: { fillColor: maroon, textColor: [255, 255, 255] },
      styles: { textColor: [0, 0, 0] }, // Keep body text black
    });
  
    // Content Table
    const detailsTableData = [
      ["Programme:", courseData.courseName],
      ["Exam Category:", "Regular Examination"],
      ["Exam Type:", courseData.examType],
      ["Exam Season:", "Second Half - Winter Examination 2023"],
      ["Number of Sets Required:", courseData.paperSettingTeachers.length],
      ["Year:", courseData.year],
      ["Semester:", courseData.semester],
      ["Course Name:", courseName],
      ["Course Code:", courseData.courseCode],
    ];
  
    autoTable(doc, {
      body: detailsTableData,
      startY: doc.previousAutoTable.finalY + 10,
      theme: "grid", // Plain table style
      styles: { textColor: [0, 0, 0] },
    });
  
    // Footer Section
    const footerY = doc.previousAutoTable.finalY + 10; // Dynamic Y-coordinate
    doc.setFontSize(12);
    doc.text("Dr. S. K. Ukarande", 10, footerY);
    doc.text("Principal", 10, footerY + 5);
    doc.text("K. J. Somaiya School of Engineering", 10, footerY + 10);
  
    // Footer Contact Details
    const footerContactY = footerY + 20;
    doc.setFontSize(10);
    doc.text(
      "Somaiya Vidyavihar, Vidyavihar (East), Mumbai-400 022, India",
      10,
      footerContactY
    );
    doc.text("Telephone: (91-22) 44444400, 44444404", 10, footerContactY + 5);
    doc.text("Email: principal.tech@somaiya.edu", 10, footerContactY + 10);
    doc.text("Web: www.somaiya.edu/kjsieit", 10, footerContactY + 15);
  
    // Save PDF
    doc.save(`${courseName} - AppointmentOrder.pdf`);
  };
  

  return (
    <>
    <Navbar/>
    <div>
      <h1 style={{ textAlign: "center" }}>
        Course Tables with Download Options
      </h1>

      <div
        style={{
          maxHeight: "70vh",
          overflowY: "auto",
          border: "1px solid #ccc",
          padding: "10px",
          borderRadius: "5px",
          backgroundColor: "#f9f9f9",
        }}
      >
        {currentCourses.map((courseCode, index) => {
          const courseData = data.filter(
            (row) => row.courseCode === courseCode
          );
          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={() => generateAppointmentPDF(courseData[0], courseName)}
                  className="btn btn-primary"
                  style={{
                    padding: "10px 15px",
                    backgroundColor: "#007bff",
                    color: "white",
                    textDecoration: "none",
                    borderRadius: "5px",
                  }}
                >
                  Download {courseName}'s Appointment Order
                </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}</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}</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}</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}</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}</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}</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>
    </>
  );
};

export default CourseConsolidated;
