import React, { useState, useEffect } from "react";
import axios from "axios";
import * as XLSX from "xlsx-js-style";
import { sendEmail } from "../api";
import { createExcelBook } from "../api";

const ConsolidatedTable = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const tablesPerPage = 5;
  const [expandedTeacher, setExpandedTeacher] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(
          "http://localhost:8080/api/table/consolidated-table"
        );
        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 faculty names
  const uniqueTeachers = [...new Set(data.map((row) => row.Name))];

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

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

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

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

  const createExcelFile = (teacherData, teacherName) => {
    const workbook = createExcelBook(teacherData, teacherName);
    XLSX.writeFile(workbook, `${teacherName.replace(/\s+/g, "_")}_Table.xlsx`);
  };

  const bulkDownload = () => {
    uniqueTeachers.forEach((teacher) => {
      const teacherData = data.filter((row) => row.Name === teacher);
      createExcelFile(teacherData, teacher);
    });
  };

  const handleSendEmail = async (teacher, teacherData) => {
    const facultyId = teacherData[0].facultyId; // This assumes all rows for a teacher have the same facultyId
    try {
      const response = await axios.get(
        `http://localhost:8080/api/faculty/${facultyId}`
      );
      const facultyEmail = response.data.email;
      const workbook = createExcelBook(teacherData, teacher);
      const fileName = `${teacher.replace(/\s+/g, "_")}_table.xlsx`;
      const excelBlob = XLSX.write(workbook, {
        bookType: "xlsx",
        type: "array",
      });

      const file = new File([excelBlob], fileName, {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      const formData = new FormData();
      formData.append("teacher", teacher);
      formData.append("fileName", fileName);
      formData.append("recipientEmail", facultyEmail);
      formData.append("file", file);

      try {
        const response = await sendEmail(formData);
        alert(`Email sent successfully to ${facultyEmail}`);
        console.log("Response from server:", response);
      } catch (error) {
        console.error("Error sending email:", error);
        alert("Failed to send email.");
      }
    } catch (error) {
      console.error("Error fetching Faculty data:", error);
      alert("Failed to fetch faculty data.");
    }
  };

  // Send emails to all teachers
  const sendEmailsToAllTeachers = async () => {
    for (let teacher of uniqueTeachers) {
      const teacherData = data.filter((row) => row.Name === teacher);
      await handleSendEmail(teacher, teacherData); // Wait for each email to be sent before proceeding to the next
    }
    alert("Emails sent to all teachers.");
  };

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

      <div style={{ marginBottom: "20px", textAlign: "center" }}>
        <button
          onClick={bulkDownload}
          className="btn btn-primary"
          style={{
            padding: "10px 15px",
            backgroundColor: "#17a2b8",
            color: "white",
            textDecoration: "none",
            borderRadius: "5px",
            marginRight: "10px",
          }}
        >
          Bulk Download All Tables
        </button>
        <button
          onClick={() => createExcelFile(data, "Consolidated Table")}
          className="btn btn-primary"
          style={{
            padding: "10px 15px",
            backgroundColor: "#28a745",
            color: "white",
            textDecoration: "none",
            borderRadius: "5px",
          }}
        >
          Download Consolidated Table
        </button>

        <button
          onClick={sendEmailsToAllTeachers}
          className="btn btn-danger"
          style={{
            padding: "10px 15px",
            backgroundColor: "#dc3545",
            color: "white",
            textDecoration: "none",
            borderRadius: "5px",
            marginLeft: "10px",
          }}
        >
          Send Emails to All Teachers
        </button>
      </div>

      <div
        style={{
          maxHeight: "70vh",
          overflowY: "auto",
          border: "1px solid #ccc",
          padding: "10px",
          borderRadius: "5px",
          backgroundColor: "#f9f9f9",
        }}
      >
        {currentTeachers.map((teacher, index) => {
          const teacherData = data.filter((row) => row.Name === teacher);
          return (
            <div key={index} style={{ marginBottom: "20px" }}>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  cursor: "pointer",
                  backgroundColor: "#ffffff",
                  color: "white",
                  padding: "10px",
                  borderRadius: "5px",
                }}
                onClick={() => setExpandedTeacher(expandedTeacher === teacher ? null : teacher)}
              >
                <h2 style={{color:'black', margin: 0 }}>{teacher}'s Table</h2>
                <div>
                  <button
                    onClick={() => createExcelFile(teacherData, teacher)}
                    className="btn btn-primary"
                    style={{
                      padding: "10px 15px",
                      backgroundColor: "#007bff",
                      color: "black",
                      textDecoration: "none",
                      borderRadius: "5px",
                      marginRight: "10px",
                    }}
                  >
                    Download {teacher}'s Table
                  </button>
                  <button
                    onClick={() => handleSendEmail(teacher, teacherData)}
                    className="btn btn-secondary"
                    style={{
                      padding: "10px 15px",
                      backgroundColor: "#6c757d",
                      color: "white",
                      textDecoration: "none",
                      borderRadius: "5px",
                    }}
                  >
                    Send {teacher}'s CSV via Email
                  </button>
                </div>
              </div>

              {expandedTeacher === teacher && (
                <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>Marks</th>
                      <th>Name</th>
                      <th>Affiliation/College</th>
                      <th>Highest Qualification</th>
                      <th>Career Experience</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>
                    {teacherData.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.marks}</td>
                        <td>{row.Name}</td>
                        <td>{row.affiliation}</td>
                        <td>{row.qualification}</td>
                        <td>{row.experience}</td>
                        <td>{row.oralPractical}</td>
                        <td>{row.assessment}</td>
                        <td>{row.reassessment}</td>
                        <td>{row.paperSetting}</td>
                        <td>{row.moderation}</td>
                        <td>{row.pwdPaperSetting}</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 ConsolidatedTable;
