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";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import Footer from "./Footer";

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: "52px",
    gap: "15px",
    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%",
    flexGrow: 1
  },
};

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);

  const getAcademicYears = () => {
    const currentYear = new Date().getFullYear();
    return Array.from({ length: 6 }, (_, i) => {
      const startYear = currentYear - i;
      const endYear = (startYear + 1).toString().slice(-2); // Get last two digits
      return `${startYear}-${endYear}`;
    });
  };

  const academicYears = getAcademicYears();
  const [selectedYear, setSelectedYear] = useState(academicYears[0]); // Default to current academic year

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

  // Filter data based on search query and selected academic year
  const filteredData = data.filter(
    (row) =>
      row.academicYear === selectedYear && // Filter by selected academic year
      row.Name.toLowerCase().includes(searchQuery.toLowerCase()) // Filter by search query
  );

  // 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}`,
        { withCredentials: true }
      );
      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, "excel");
        toast.success(`Email sent successfully to ${facultyEmail}`);
        console.log("Response from server:", emailResponse);
      } catch (emailError) {
        console.error("Error sending email:", emailError);
        toast.error("Failed to send email.");
      }
    } catch (facultyError) {
      console.error("Error fetching Faculty data:", facultyError);
      toast.error("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
    }
    toast.success("Emails sent to all teachers.");
  };

  return (
    <div style={{
      display:"flex",
      flexDirection:"column",
      minHeight: "100vh"
    }}>
      <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",
            }}
          />
          {/* Academic Year Dropdown */}
          <select
            value={selectedYear}
            onChange={(e) => setSelectedYear(e.target.value)}
          >
            {academicYears.map((year) => (
              <option key={year} value={year}>
                {year}
              </option>
            ))}
          </select>
        </div>

        <div style={styles.tableContainer}>
          {currentTeachers.map((teacher, index) => {
            const teacherData = filteredData.filter((row) => row.Name === teacher);
            console.log(teacherData);
            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
                    </button>
                    <button
                      onClick={() => handleSendEmail(teacher, teacherData)}
                      style={{
                        ...styles.button,
                        backgroundColor: "#6c757d",
                      }}
                    >
                      Send XSL via Email
                    </button>
                  </div>
                </div>

                {expandedTeacher === teacher && (
                  <table style={styles.table}>
                    <thead>
                      <tr>
                        <th style={styles.th}>Semester</th>
                        <th style={styles.th}>Program</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}>Exam Period</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.program}</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.examPeriod + " " + row.academicYear}
                          </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>
      <Footer/>
    </div>
  );
};

export default ConsolidatedTable;
