import { useState, useEffect } from 'react'
import { useAuth } from '../../hooks/useAuth';
import { getSharedDocuments } from '../../services/api';

function Clients() {
  const [documents, setDocuments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const { user } = useAuth();

  useEffect(() => {
    const fetchDocuments = async () => {
      try {
        const response = await getSharedDocuments(user.id);
        setDocuments(response.data);
      } catch (err) {
        setError('Failed to fetch documents');
        console.error('Error fetching documents:', err);
      } finally {
        setLoading(false);
      }
    };

    if (user) {
      fetchDocuments();
    }
  }, [user]);

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-screen">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center text-red-600 p-4">
        {error}
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-2xl font-bold mb-6">Your Documents</h1>
      
      {documents.length === 0 ? (
        <p className="text-gray-600">No documents have been shared with you yet.</p>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {documents.map((doc) => (
            <div 
              key={doc.id} 
              className="bg-white p-6 rounded-lg shadow-md hover:shadow-lg transition-shadow"
            >
              <div className="flex justify-between items-start mb-4">
                <h2 className="text-xl font-semibold">{doc.title}</h2>
                <span className={`px-2 py-1 text-xs rounded-full ${
                  doc.status === 'completed' 
                    ? 'bg-green-100 text-green-800' 
                    : 'bg-yellow-100 text-yellow-800'
                }`}>
                  {doc.status}
                </span>
              </div>
              
              <div className="text-sm text-gray-600">
                <p>Created: {new Date(doc.createdAt).toLocaleDateString()}</p>
                {doc.content && (
                  <p className="mt-2">{doc.content}</p>
                )}
              </div>
              
              <div className="mt-4 flex justify-end">
                <button 
                  onClick={() => window.open(`/api/documents/download/${doc.s3Key}`, '_blank')}
                  className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition-colors"
                >
                  Download
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default Clients;

