import { useState, useEffect } from 'react';
import { uploadDocument, getAllUsers, getUserInfo } from '../../services/api';

function DocumentUpload() {
  const [file, setFile] = useState(null);
  const [title, setTitle] = useState('');
  const [selectedUsers, setSelectedUsers] = useState([]);
  const [availableUsers, setAvailableUsers] = useState([]);
  const [status, setStatus] = useState('idle'); // idle, uploading, completed, failed
  const [errorMessage, setErrorMessage] = useState('');
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    fetchUsers();
    getCurrentUser();
  }, []);

  const fetchUsers = async () => {
    try {
      const response = await getAllUsers();
      setAvailableUsers(response.data.filter(user => !user.isAdmin));
    } catch (error) {
      setErrorMessage('Failed to load users');
    }
  };

  const getCurrentUser = async () => {
    try {
      const response = await getUserInfo();
      console.log('Current user data:', response.data); // Debug log
      setCurrentUser(response.data);
    } catch (error) {
      console.error('Failed to get current user:', error);
      setErrorMessage('Failed to get current user info');
    }
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    
    if (!file || !title || selectedUsers.length === 0 || !currentUser) {
      setErrorMessage('Please provide all required information');
      return;
    }
  
    setStatus('uploading');
    setErrorMessage('');
  
    const formData = new FormData();
    formData.append('file', file);
    formData.append('title', title);
    formData.append('sharedWithId', selectedUsers[0]); // Remove toString()
    formData.append('uploadedById', currentUser.id); // Remove toString()
  
    // Debug log
    console.log('Form Data Contents:', {
      file: formData.get('file'),
      title: formData.get('title'),
      sharedWithId: formData.get('sharedWithId'),
      uploadedById: formData.get('uploadedById')
    });
  
    try {
      const response = await uploadDocument(formData);
      console.log('Upload response:', response);
      
      setStatus('completed');
      setTitle('');
      setFile(null);
      setSelectedUsers([]);
      event.target.reset();
    } catch (error) {
      console.error('Upload error:', error);
      setStatus('failed');
      setErrorMessage(error.response?.data?.message || 'Upload failed');
    }
  };

  function handleFileChange(e) {
    setFile(e.target.files[0]);
  }

  const handleUserSelect = (e) => {
    const values = Array.from(e.target.selectedOptions, option => option.value);
    console.log('Selected user values:', values);
    setSelectedUsers(values);
  };

  return (
    <div className="max-w-md mx-auto mt-8 p-6 bg-white rounded-lg shadow-md">
      <h2 className="text-2xl font-bold mb-6">Upload Document</h2>
      
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700">
            Document Title
          </label>
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
            required
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700">
            File
          </label>
          <input
            type="file"
            onChange={handleFileChange}
            className="mt-1 block w-full"
            required
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700">
            Share with Users
          </label>
          <select
            multiple
            value={selectedUsers}
            onChange={handleUserSelect}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
            required
          >
            {availableUsers.map(user => (
              <option key={user.id} value={user.id}>
                {user.name} ({user.email})
              </option>
            ))}
          </select>
        </div>

        {errorMessage && (
          <div className="text-red-500 text-sm mt-2">
            {errorMessage}
          </div>
        )}

        <button
          type="submit"
          disabled={status === 'uploading'}
          className={`w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white 
            ${status === 'uploading' 
              ? 'bg-gray-400 cursor-not-allowed' 
              : 'bg-indigo-600 hover:bg-indigo-700'
            }`}
        >
          {status === 'uploading' ? (
            <>
              <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              Uploading...
            </>
          ) : 'Upload Document'}
        </button>

        {status === 'completed' && (
          <div className="text-green-500 text-sm mt-2">
            Document uploaded successfully!
          </div>
        )}
      </form>
    </div>
  );
}

export default DocumentUpload;