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

const styles = {
  header: {
    background: '#003366', 
    color: 'white',
    padding: '20px 0',
    textAlign: 'center',
    fontSize: '24px',
    marginBottom: '0', 
  },
  buttonRow: {
    display: 'flex',
    justifyContent: 'space-around', 
    alignItems: 'center',
    padding: '10px 0',
    margin: '0', 
    backgroundColor: '#003366', 
    boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)' 
  },
  button: {
    padding: '10px 20px',
    borderRadius: '5px',
    color: 'white',
    border: 'none',
    cursor: 'pointer',
    fontSize: '16px',
    flex: '1', 
  },
  bulkDownloadButton: {
    backgroundColor: '#3fb5a3',
  },
  downloadButton: {
    backgroundColor: '#28a745',
  },
  emailButton: {
    backgroundColor: '#ff6f61',
  },
  tableContainer: {
    maxHeight: "70vh",
    overflowY: "auto",
    border: "1px solid #ccc",
    padding: "10px",
    borderRadius: "5px",
    backgroundColor: "#f9f9f9",
    marginBottom: "20px",
  },
  table: {
    width: "100%",
    marginTop: "20px",
    borderCollapse: "collapse",
  },
  th: {
    backgroundColor: "#333",
    color: "white",
    padding: "10px 15px",
  },
  td: {
    padding: "10px",
    textAlign: "left",
    borderBottom: "1px solid #ddd",
  },
  paginationContainer: {
    textAlign: "center",
    marginTop: "20px",
  },
  paginationButton: {
    padding: "10px 15px",
    backgroundColor: "#007bff",
    color: "white",
    borderRadius: "5px",
    border: "none",
  },
  main: {
    width: "100%",
  }
};



const ConsolidatedTable = () => {
  const [searchQuery, setSearchQuery] = useState(""); // State for search input
  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 and filter based on the search query
  const filteredTeachers = [...new Set(data.map((row) => row.Name))].filter(
    (teacher) =>
      teacher.toLowerCase().includes(searchQuery.toLowerCase()) // Filter by search query
  );

  // Pagination logic applied to filtered teachers
  const indexOfLastTable = currentPage * tablesPerPage;
  const indexOfFirstTable = indexOfLastTable - tablesPerPage;
  const currentTeachers = filteredTeachers.slice(
    indexOfFirstTable,
    indexOfLastTable
  );

  const totalPages = Math.ceil(filteredTeachers.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 = () => {
    filteredTeachers.forEach((teacher) => {
      const teacherData = data.filter((row) => row.Name === teacher);
      createExcelFile(teacherData, teacher);
    });
  };

  const handleSendEmail = async (teacher, teacherData) => {
    const facultyId = teacherData[0].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 emailResponse = await sendEmail(formData);
        alert(`Email sent successfully to ${facultyEmail}`);
        console.log("Response from server:", emailResponse);
      } catch (emailError) {
        console.error("Error sending email:", emailError);
        alert("Failed to send email.");
      }
    } catch (facultyError) {
      console.error("Error fetching Faculty data:", facultyError);
      alert("Failed to fetch faculty data.");
    }
  };

  const sendEmailsToAllTeachers = async () => {
    for (let teacher of filteredTeachers) {
      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 (
    <>
      <Navbar />
      <div style={styles.main}>
        <h1 style={styles.header}>Faculty Tables with Download Options</h1>

        <div style={styles.buttonRow}>
          <button
            onClick={bulkDownload}
            style={{ ...styles.button, ...styles.bulkDownloadButton }}
          >
            Bulk Download All Tables
          </button>
          <button
            onClick={() => createExcelFile(data, "Consolidated Table")}
            style={{ ...styles.button, ...styles.downloadButton }}
          >
            Download Consolidated Table
          </button>
          <button
            onClick={sendEmailsToAllTeachers}
            style={{ ...styles.button, ...styles.emailButton }}
          >
            Send Emails to All Teachers
          </button>
        </div>

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

        <div style={styles.tableContainer}>
          {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",
                    padding: "10px",
                    borderRadius: "5px",
                    backgroundColor: "#ffffff",
                    boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
                  }}
                  onClick={() =>
                    setExpandedTeacher(
                      expandedTeacher === teacher ? null : teacher
                    )
                  }
                >
                  <h2
                    style={{ color: "black", margin: 0, fontSize: "1.5rem" }}
                  >
                    {teacher}'s Table
                  </h2>
                  <div>
                    <button
                      onClick={() => createExcelFile(teacherData, teacher)}
                      style={{ ...styles.button, backgroundColor: "#007bff" }}
                    >
                      Download {teacher}'s Table
                    </button>
                    <button
                      onClick={() => handleSendEmail(teacher, teacherData)}
                      style={{
                        ...styles.button,
                        backgroundColor: "#6c757d",
                      }}
                    >
                      Send {teacher}'s XSL via Email
                    </button>
                  </div>
                </div>

                {expandedTeacher === teacher && (
                  <table style={styles.table}>
                    <thead>
                      <tr>
                        <th style={styles.th}>Semester</th>
                        <th style={styles.th}>Course Code</th>
                        <th style={styles.th}>Course Name</th>
                        <th style={styles.th}>Exam Type</th>
                        <th style={styles.th}>Year</th>
                        <th style={styles.th}>Marks</th>
                        <th style={styles.th}>Name</th>
                        <th style={styles.th}>Affiliation/College</th>
                        <th style={styles.th}>Highest Qualification</th>
                        <th style={styles.th}>Career Experience</th>
                        <th style={styles.th}>Oral/Practical</th>
                        <th style={styles.th}>Assessment</th>
                        <th style={styles.th}>Reassessment</th>
                        <th style={styles.th}>Paper Setting</th>
                        <th style={styles.th}>Moderation</th>
                        <th style={styles.th}>PwD Paper Setting</th>
                      </tr>
                    </thead>
                    <tbody>
                      {teacherData.map((row, idx) => (
                        <tr key={idx}>
                          <td style={styles.td}>{row.semester}</td>
                          <td style={styles.td}>{row.courseCode}</td>
                          <td style={styles.td}>{row.courseName}</td>
                          <td style={styles.td}>{row.examType}</td>
                          <td style={styles.td}>{row.year}</td>
                          <td style={styles.td}>{row.marks}</td>
                          <td style={styles.td}>{row.Name}</td>
                          <td style={styles.td}>{row.affiliation}</td>
                          <td style={styles.td}>{row.qualification}</td>
                          <td style={styles.td}>{row.experience}</td>
                          <td style={styles.td}>{row.oralPractical}</td>
                          <td style={styles.td}>{row.assessment}</td>
                          <td style={styles.td}>{row.reassessment}</td>
                          <td style={styles.td}>{row.paperSetting}</td>
                          <td style={styles.td}>{row.moderation}</td>
                          <td style={styles.td}>{row.pwdPaperSetting}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
              </div>
            );
          })}
        </div>

        {/* Pagination controls */}
        <div style={styles.paginationContainer}>
          <button
            onClick={handlePrevPage}
            disabled={currentPage === 1}
            style={{
              ...styles.paginationButton,
              backgroundColor: currentPage === 1 ? "#ccc" : "#007bff",
            }}
          >
            Previous
          </button>
          <span>
            Page {currentPage} of {totalPages}
          </span>
          <button
            onClick={handleNextPage}
            disabled={currentPage === totalPages}
            style={{
              ...styles.paginationButton,
              backgroundColor: currentPage === totalPages ? "#ccc" : "#007bff",
            }}
          >
            Next
          </button>
        </div>
      </div>
    </>
  );
};

export default ConsolidatedTable;
