// Page5.js

import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import './Page5.css';
import somaiyatrust from './components/somaiyatrust.png';
import image from './components/image.png';
import redlines from './components/redlines.png';

const Page5 = () => {
  const [meetings, setMeetings] = useState([]);
  const [expandedIndex, setExpandedIndex] = useState(null);

  const fetchMeetings = () => {
    axios.get('http://localhost:5000/api/meetings')
      .then((response) => {
        const sortedMeetings = response.data.sort((a, b) => {
          const dateA = new Date(`${a.date}T${a.startTime}`);
          const dateB = new Date(`${b.date}T${b.startTime}`);
          return dateB - dateA;
        });
        setMeetings(sortedMeetings);
      })
      .catch((error) => {
        console.error('Error fetching meetings:', error);
      });
  };

  useEffect(() => {
    fetchMeetings();
  }, []);

  const toggleExpand = (index) => {
    setExpandedIndex(prev => (prev === index ? null : index));
  };

  const handleSoftDelete = async (id) => {
    try {
      await axios.patch(`http://localhost:5000/api/meetings/${id}/soft-delete`);
      alert('Meeting soft deleted!');
      fetchMeetings();
    } catch (error) {
      console.error('Error deleting meeting:', error);
      alert('Soft delete failed.');
    }
  };

  return (
    <div className="page-container">
      <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>

      <nav className="navbar">
        <ul>
          <li><Link to="/page2">Home</Link></li>
          <li><Link to="/page3">Schedule</Link></li>
          <li><Link to="/page5" className="active">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>

      <div className="meetings-page-container">
        <h1 className="page-title">Meeting Details</h1>

        {meetings.length === 0 ? (
          <p className="no-meetings">No meetings available</p>
        ) : (
          <div className="meetings-grid-container">
            <div className="meetings-grid">
              {meetings.map((meeting, index) => (
                <div 
                  key={index} 
                  className={`meeting-card ${expandedIndex === index ? 'expanded' : ''}`}
                >
                  <div className="card-summary" onClick={() => toggleExpand(index)}>
                    <h2 className="meeting-title">{meeting.subject}</h2>
                    <div className="meeting-meta">
                      <span className="meeting-date">{meeting.date}</span>
                      <span className="meeting-time">{meeting.startTime} - {meeting.endTime}</span>
                    </div>
                    <div className="meeting-department">{meeting.department}</div>
                  </div>

                  {expandedIndex === index && (
                    <div className="card-details">
                      <div className="detail-row">
                        <span className="detail-label">Program:</span>
                        <span>{meeting.program}</span>
                      </div>

                      <div className="detail-section">
                        <h3>Agenda</h3>
                        {meeting.agenda && meeting.agenda.length > 0 ? (
                          <ul className="agenda-list">
                            {meeting.agenda.map((item, idx) => (
                              <li key={idx}>{item}</li>
                            ))}
                          </ul>
                        ) : (
                          <p>No agenda provided</p>
                        )}
                      </div>

                      <div className="detail-section">
                        <h3>Details</h3>
                        <p>{meeting.body}</p>
                      </div>

                      <div className="detail-section">
                        <h3>Recipients</h3>
                        <div className="recipients-list">
                          {meeting.recipients.join(', ')}
                        </div>
                      </div>

                      <div className="detail-section">
                        <h3>Attachments</h3>
                        {meeting.attachments && meeting.attachments.length > 0 ? (
                          <ul className="attachments-list">
                            {meeting.attachments.map((file, idx) => (
                              <li key={idx}>
                                <a 
                                  href={`/uploads/${file.filename}`} 
                                  target="_blank" 
                                  rel="noopener noreferrer"
                                  onClick={(e) => e.stopPropagation()}
                                >
                                  {file.filename}
                                </a>
                              </li>
                            ))}
                          </ul>
                        ) : (
                          <p>No attachments available</p>
                        )}
                      </div>

                      <a
                        href={`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${encodeURIComponent(
                          meeting.subject
                        )}&details=${encodeURIComponent(meeting.body)}&dates=${meeting.date}T${meeting.startTime}/${meeting.date}T${meeting.endTime}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="calendar-button"
                        onClick={(e) => e.stopPropagation()}
                      >
                        Add to Google Calendar
                      </a>

                      {/* ✅ Soft Delete Button */}
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleSoftDelete(meeting._id);
                        }}
                        className="soft-delete-button"
                      >
                        Delete Meeting
                      </button>

                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

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

export default Page5;
