//Page4.js

import React, { useState } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import './Page2.css';
import './Page4.css';
import { FaTimes } from "react-icons/fa";
import image from './components/image.png';
import somaiyatrust from './components/somaiyatrust.png';
import redlines from './components/redlines.png';
import { useEffect } from "react";

const Page4 = () => {
  const [programs, setPrograms] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [departmentEmails, setDepartmentEmails] = useState([]);
  const [program, setProgram] = useState("");
  const [department, setDepartment] = useState("");
  const [subject, setSubject] = useState("");
  const [body, setBody] = useState("");
  const [agenda, setAgenda] = useState([""]);
  const [date, setDate] = useState("");
  const [startTime, setStartTime] = useState("");
  const [endTime, setEndTime] = useState("");
  const [recipients, setRecipients] = useState([""]);
  const [attachments, setAttachments] = useState([]);

  useEffect(() => {
    axios.get("http://localhost:5000/api/programs")
      .then(response => setPrograms(response.data))
      .catch(error => console.error("Error fetching programs:", error));
  }, []);

  useEffect(() => {
    if (program) {
      axios.get(`http://localhost:5000/api/departments/${program}`)
        .then(response => setDepartments(response.data))
        .catch(error => console.error("Error fetching departments:", error));
    } else {
      setDepartments([]);
    }
  }, [program]);

  useEffect(() => {
    if (department) {
      axios.get(`http://localhost:5000/api/department-emails/${department}`)
        .then(response => {
          setDepartmentEmails(response.data.emails);
          setRecipients([...response.data.emails]);
        })
        .catch(error => console.error("Error fetching department emails:", error));
    }
  }, [department]);
    
  const addAgenda = () => setAgenda([...agenda, ""]);
  const handleAgendaChange = (index, value) => {
    const updatedAgenda = [...agenda];
    updatedAgenda[index] = value;
    setAgenda(updatedAgenda);
  };
  const removeAgenda = (index) => {
    const updatedAgenda = agenda.filter((_, i) => i !== index);
    setAgenda(updatedAgenda);
  };

  const addRecipient = () => setRecipients([...recipients, ""]);
  const handleRecipientChange = (index, value) => {
    const updatedRecipients = [...recipients];
    updatedRecipients[index] = value;
    setRecipients(updatedRecipients);
  };
  const removeRecipient = (index) => {
    const updatedRecipients = recipients.filter((_, i) => i !== index);
    setRecipients(updatedRecipients);
  };

  const handleFileChange = (event) => {
    setAttachments(event.target.files);
  };

  const sendEmail = async () => {
    if (!department || !subject || !body || !date || !startTime || !endTime || recipients.length === 0) {
      alert("All fields are required!");
      return;
    }

    const formData = new FormData();
    formData.append("program", program);
    formData.append("department", department);
    formData.append("subject", subject);
    formData.append("body", body);
    formData.append("date", date);
    formData.append("startTime", startTime);
    formData.append("endTime", endTime);
    recipients.forEach((email) => formData.append("recipients", email));
    agenda.forEach((item) => formData.append("agenda", item));
    Array.from(attachments).forEach((file) => formData.append("attachments", file));

    try {
      const response = await axios.post("http://localhost:5000/api/send-email", formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });
      alert(response.data.message);
    } catch (err) {
      if (err.response?.status === 409) {
        const conflictDetails = err.response.data.conflictDetails;
        alert(`Conflict Detected :
          Department: ${conflictDetails.department}
          Date: ${conflictDetails.date}
          Time: ${conflictDetails.startTime} - ${conflictDetails.endTime}
          Recipients: ${conflictDetails.recipients.join(", ")}
          Subject: ${conflictDetails.subject}
        `);
      } else {
        alert(err.response?.data?.error || "Error sending email");
      }
    }
  };

  return (
    <div className="page-container">
      {/* Header Bar */}
      <header className="header-bar">
        <img src={image} alt="Left Logo" className="leftlogo" />
        <h1 className="college-name">Somaiya Scheduler</h1>
        <img src={somaiyatrust} alt="Right Logo" className="rightlogo" />
      </header>

      {/* Navigation Bar */}
      <nav className="navbar">
        <ul>
          <li><Link to="/page2">Home</Link></li>
          <li><Link to="/page3">Schedule</Link></li>
          <li><Link to="/page5">Meeting DataBase</Link></li>
          <li><Link to="/page6">Edit DataBase</Link></li>
          <li><Link to="/">Log Out</Link></li>
        </ul>
      </nav>

      {/* Main Content Container */}
      <div className="main-container">
        {/* Stream Bar (Left Side) */}
        <div className="stream-bar">
          <h3>Streams</h3>
          <ul>
            {["Engineering & Technology", "Management Studies", "Education", "Dharama Studies", "Commerce & Business Studies", "Science", "Humanities & Social Science", "Music Performance & Art", "Language & Literature"].map((stream) => (
              <li key={stream} onClick={() => alert(`Selected: ${stream}`)}>{stream}</li>
            ))}
          </ul>
        </div>

        {/* Content Area (Right Side) */}
        <div className="content-area">
          <h1>BOS Email Management System</h1>
          <label>Programme:</label>
          <select onChange={(e) => setProgram(e.target.value)} value={program}>
            <option value="">Choose a Programme</option>
            {programs.map((prog, idx) => (
              <option key={idx} value={prog.name}>{prog.name}</option>
            ))}
          </select>

          <label>Department:</label>
          <select onChange={(e) => setDepartment(e.target.value)} value={department}>
            <option value="">Choose a Department</option>
            {departments.map((dept, idx) => (
              <option key={idx} value={dept}>
                {dept}
              </option>
            ))}
          </select>

          <label>Subject:</label>
          <input type="text" placeholder="Subject" value={subject} onChange={(e) => setSubject(e.target.value)} />

          <label>Body:</label>
          <textarea placeholder="Body" value={body} onChange={(e) => setBody(e.target.value)} />

          <label>Agenda:</label>
          {agenda.map((item, index) => (
            <div key={index} style={{ display: "flex", alignItems: "center" }}>
              <input
                type="text"
                placeholder="Agenda item"
                value={item}
                onChange={(e) => handleAgendaChange(index, e.target.value)}
              />
              <FaTimes
                style={{ color: "red", cursor: "pointer", marginLeft: "10px" }}
                onClick={() => removeAgenda(index)}
              />
            </div>
          ))}
          <button onClick={addAgenda}>+ Add Agenda</button>

          <label>Date:</label>
          <input type="date" value={date} onChange={(e) => setDate(e.target.value)} />

          <label>Start Time:</label>
          <input type="time" value={startTime} onChange={(e) => setStartTime(e.target.value)} />

          <label>End Time:</label>
          <input type="time" value={endTime} onChange={(e) => setEndTime(e.target.value)} />

          <label>Recipient Emails:</label>
          {recipients.map((email, index) => (
            <div key={index} style={{ display: "flex", alignItems: "center" }}>
              <input
                type="email"
                placeholder="Recipient Email"
                value={email}
                onChange={(e) => handleRecipientChange(index, e.target.value)}
              />
              <FaTimes
                style={{ color: "red", cursor: "pointer", marginLeft: "10px" }}
                onClick={() => removeRecipient(index)}
              />
            </div>
          ))}
          <button onClick={addRecipient}>+ Add Recipient</button>

          <label>Attachments:</label>
          <input type="file" multiple onChange={handleFileChange} />

          <button onClick={sendEmail}>Send Email</button>
        </div>
      </div>

      {/* Footer */}
      <footer>
        <div className="terms">
          <a href="#">Terms and Policies</a>
          <img src={redlines} alt="Footer Logo" className="footer-image" />
        </div>
      </footer>
    </div>
  );
};

export default Page4;
