import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import './Library.css';

const Library = () => {
  const [libraryItems, setLibraryItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    const token = localStorage.getItem('token');
    if (!token) {
      navigate('/login', {
        state: {
          message: 'Please log in to access your library',
          redirectAfterLogin: '/library',
        },
      });
      return;
    }

    fetchLibraryItems();
  }, [navigate]);

  const fetchLibraryItems = async () => {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch('http://192.168.2.5:3006/api/lib/library', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.ok) {
        const data = await response.json();
        setLibraryItems(data.library);
      } else {
        console.error('Failed to fetch library items');
        if (response.status === 401) {
          handleLogout();
        }
      }
      setLoading(false);
    } catch (error) {
      console.error('Error fetching library:', error);
      setLoading(false);
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('userId');
    localStorage.removeItem('username');
    navigate('/login');
  };

  const removeFromLibrary = async (documentId) => {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(
        `http://192.168.2.5:3006/api/lib/library/remove/${documentId}`,
        {
          method: 'DELETE',
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      if (response.ok) {
        // Since we filter by `documentId`, only the selected file will be removed
        setLibraryItems(libraryItems.filter((item) => item.documentId !== documentId));
      } else {
        alert('Failed to remove document');
      }
    } catch (error) {
      console.error('Error removing document:', error);
      alert('Network error. Could not remove document.');
    }
  };

  if (loading) return <div>Loading...</div>;

  return (
    <div className="library-container">
      <div className="header">
        <h2>My Library</h2>
        <button onClick={handleLogout} className="logout-button">
          Logout
        </button>
      </div>

      {libraryItems.length === 0 ? (
        <p>No documents in your library yet.</p>
      ) : (
        <div className="library-list">
          {libraryItems.map((item) => (
            <div key={item.documentId} className="library-item">
              {/* Filename */}
              <div className="library-details">
                <a
                  href={`http://192.168.2.5:3006/files/${encodeURIComponent(
                    item.filename
                  )}`}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  {item.filename}
                </a>
              </div>
              
             
              <div className="metadata-row">
                <span className="added-date">
                  Added on: {new Date(item.addedAt).toLocaleDateString()}
                </span>
                
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default Library;    in this with added on add a remove button also for each file and ..remove will only remove that file only not whole libaray need to be cleared  /* Main Container for Library */
.library-container {
  max-width: 900px;
  margin: 50px auto;
  padding: 20px;
  background-color: #f4f4f4;
  border-radius: 8px;
  font-family: Arial, sans-serif;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

/* Responsive Header */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 24px;
}

.logout-button {
  padding: 8px 12px;
  border: none;
  background-color: #e74c3c;
  color: #fff;
  border-radius: 4px;
  cursor: pointer;
}

.logout-button:hover {
  background-color: #c0392b;
}

/* Scrollable Section for Library Items */
.library-list {
  max-height: 500px; /* Limit the height for scrolling */
  overflow-y: auto;
  padding: 10px;
  background: #ffffff;
  border-radius: 8px;
}

/* Styling for Each Library Item */
.library-item {
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 5px;
  margin-bottom: 15px;
  padding: 15px;
  display: flex;
  flex-direction: column;
}

/* Filename */
.library-details a {
  font-size: 16px;
  color: #007bff;
  text-decoration: none;
  word-break: break-word;
}

.library-details a:hover {
  text-decoration: underline;
}

/* Metadata Row */
.metadata-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.added-date {
  font-size: 14px;
  color: #777;
}

/* Remove Button */
.remove-button {
  padding: 6px 12px;
  background-color: #e74c3c;
  color: white;
  font-size: 13px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.remove-button:hover {
  background-color: #c0392b;
}  dont chnge any other thing ..provide complete upated code