import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { FaEdit, FaTrash, FaPlus, FaSave, FaTimes } from 'react-icons/fa';
import './Page6.css';
import image from './components/image.png';
import somaiyatrust from './components/somaiyatrust.png';
import redlines from './components/redlines.png';

const Page6 = () => {
  const [departments, setDepartments] = useState([]);
  const [programs, setPrograms] = useState([]);
  const [newDepartment, setNewDepartment] = useState('');
  const [newEmails, setNewEmails] = useState(['']);
  const [selectedProgram, setSelectedProgram] = useState('');
  const [editingDepartment, setEditingDepartment] = useState(null);
  const [isAddingNew, setIsAddingNew] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    fetchDepartments();
    fetchPrograms();
  }, []);

  const fetchDepartments = async () => {
    try {
      const response = await axios.get('http://localhost:5000/api/department-emails');
      setDepartments(response.data);
    } catch (error) {
      console.error('Error fetching departments:', error);
    }
  };

  const fetchPrograms = async () => {
    try {
      const response = await axios.get('http://localhost:5000/api/programs');
      setPrograms(response.data);
    } catch (error) {
      console.error('Error fetching programs:', error);
    }
  };

  const handleAddEmail = () => {
    setNewEmails([...newEmails, '']);
  };

  const handleNewEmailChange = (index, value) => {
    const updatedEmails = [...newEmails];
    updatedEmails[index] = value;
    setNewEmails(updatedEmails);
  };

  const handleRemoveEmail = (index) => {
    const updatedEmails = newEmails.filter((_, i) => i !== index);
    setNewEmails(updatedEmails);
  };

  const startEditing = (department) => {
    setEditingDepartment(department);
    setNewEmails([...department.emails]);
    setIsAddingNew(false);
  };

  const cancelEditing = () => {
    setEditingDepartment(null);
    setIsAddingNew(false);
    setNewDepartment('');
    setNewEmails(['']);
    setSelectedProgram('');
  };

  const saveDepartment = async () => {
    try {
      const emailsToSave = newEmails.filter(email => email.trim() !== '');

      if (emailsToSave.length === 0) {
        alert('At least one email is required');
        return;
      }

      if (isAddingNew) {
        if (!newDepartment.trim()) {
          alert('Department name is required');
          return;
        }
        if (!selectedProgram) {
          alert('Please select a program');
          return;
        }

        await axios.post('http://localhost:5000/api/department-emails', {
          department: newDepartment,
          emails: emailsToSave,
          program: selectedProgram,
        });
      } else {
        await axios.put(`http://localhost:5000/api/department-emails/${editingDepartment.department}`, {
          emails: emailsToSave
        });
      }

      fetchDepartments();
      cancelEditing();
    } catch (error) {
      console.error('Error saving department:', error);
      alert('Error saving department. Please try again.');
    }
  };

  const deleteDepartment = async (departmentName) => {
    if (window.confirm(`Are you sure you want to delete ${departmentName}?`)) {
      try {
        await axios.delete(`http://localhost:5000/api/department-emails/${departmentName}`);
        fetchDepartments();
      } catch (error) {
        console.error('Error deleting department:', error);
        alert('Error deleting department. Please try again.');
      }
    }
  };

  const filteredDepartments = departments.filter(dept =>
    dept.department.toLowerCase().includes(searchTerm.toLowerCase())
  );

  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">Manage Emails</Link></li>
          <li><a href="#">Contact</a></li>
          <li><Link to="/">Log Out</Link></li>
        </ul>
      </nav>

      {/* Main Content */}
      <div className="email-management-container">
        <h1>Department Email Management</h1>

        <div className="search-bar">
          <input
            type="text"
            placeholder="Search departments..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>

        {editingDepartment || isAddingNew ? (
          <div className="edit-form">
            <h2>{isAddingNew ? 'Add New Department' : `Editing: ${editingDepartment.department}`}</h2>

            {isAddingNew && (
              <>
                <div className="form-group">
                  <label>Program:</label>
                  <select
                    value={selectedProgram}
                    onChange={(e) => setSelectedProgram(e.target.value)}
                  >
                    <option value="">Select Program</option>
                    {programs.map((prog, idx) => (
                      <option key={idx} value={prog.name}>{prog.name}</option>
                    ))}
                  </select>
                </div>

                <div className="form-group">
                  <label>Department Name:</label>
                  <input
                    type="text"
                    value={newDepartment}
                    onChange={(e) => setNewDepartment(e.target.value)}
                    placeholder="Enter department name"
                  />
                </div>
              </>
            )}

            <div className="form-group">
              <label>Emails:</label>
              {newEmails.map((email, index) => (
                <div key={index} className="email-input-group">
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => handleNewEmailChange(index, e.target.value)}
                    placeholder="Enter email"
                  />
                  {newEmails.length > 1 && (
                    <button
                      type="button"
                      className="remove-email"
                      onClick={() => handleRemoveEmail(index)}
                    >
                      <FaTimes />
                    </button>
                  )}
                </div>
              ))}
              <button
                type="button"
                className="add-email"
                onClick={handleAddEmail}
              >
                <FaPlus /> Add Email
              </button>
            </div>

            <div className="form-actions">
              <button type="button" className="save-btn" onClick={saveDepartment}>
                <FaSave /> Save
              </button>
              <button type="button" className="cancel-btn" onClick={cancelEditing}>
                <FaTimes /> Cancel
              </button>
            </div>
          </div>
        ) : (
          <>
            <button
              className="add-department-btn"
              onClick={() => {
                setIsAddingNew(true);
                setEditingDepartment(null);
              }}
            >
              <FaPlus /> Add New Department
            </button>

            <div className="departments-list">
              {filteredDepartments.length === 0 ? (
                <p>No departments found</p>
              ) : (
                filteredDepartments.map((dept) => (
                  <div key={dept._id} className="department-card">
                    <h3>{dept.department}</h3>
                    <ul>
                      {dept.emails.map((email, idx) => (
                        <li key={idx}>{email}</li>
                      ))}
                    </ul>
                    <div className="department-actions">
                      <button onClick={() => startEditing(dept)} className="edit-btn">
                        <FaEdit /> Edit
                      </button>
                      <button onClick={() => deleteDepartment(dept.department)} className="delete-btn">
                        <FaTrash /> Delete
                      </button>
                    </div>
                  </div>
                ))
              )}
            </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 Page6;
