import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { getAllDocuments } from "../../services/api";
import { getAllUsers } from "../../services/api";
import {
  FiUsers,
  FiFile,
  FiUpload,
  FiKey,
  FiLoader,
  FiUserPlus,
} from "react-icons/fi";

function Documents() {
  const [documents, setDocuments] = useState([]);
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const [documentsResponse, usersResponse] = await Promise.all([
          getAllDocuments(),
          getAllUsers(),
        ]);

        // Make sure we're getting the data property from the response
        setDocuments(
          Array.isArray(documentsResponse.data) ? documentsResponse.data : [],
        );
        setUsers(Array.isArray(usersResponse.data) ? usersResponse.data : []);
      } catch (error) {
        console.error("Error fetching data:", error);
        setError("Failed to load data");
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center p-8">
        <FiLoader className="w-8 h-8 animate-spin text-primary-500" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg text-red-200">
        {error}
      </div>
    );
  }

  return (
    <div className="bg-primary-800/50 backdrop-blur-lg rounded-xl overflow-hidden shadow-xl">
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="border-b border-primary-700">
              <th className="px-6 py-4 text-left text-md text-neutral-400">
                Име
              </th>
              <th className="px-6 py-4 text-left text-md text-neutral-400">
                Прикачено од
              </th>
              <th className="px-6 py-4 text-left text-md text-neutral-400">
                Споделено со
              </th>
              <th className="px-6 py-4 text-left text-md text-neutral-400">
                Креирано на
              </th>
            </tr>
          </thead>
          <tbody>
            {documents.length > 0 ? (
              documents.map((doc) => (
                <tr
                  key={doc.id}
                  className="border-b border-primary-700/50 hover:bg-primary-700/30"
                >
                  <td className="px-6 py-4 text-white">{doc.title || "N/A"}</td>
                  <td className="px-6 py-4 text-neutral-300">
                    {doc.uploadedBy ? (
                      <>
                        {doc.uploadedBy.name} ({doc.uploadedBy.email})
                      </>
                    ) : (
                      "N/A"
                    )}
                  </td>
                  <td className="px-6 py-4 text-neutral-300">
                    {doc.sharedWith && doc.sharedWith.length > 0 ? (
                      <div className="whitespace-nowrap">
                        {doc.sharedWith.map((user) => (
                          <div key={user.id}>
                            {user.name} ({user.email})
                          </div>
                        ))}
                      </div>
                    ) : (
                      "None"
                    )}
                  </td>
                  <td className="px-6 py-4 text-neutral-300">
                    {doc.createdAt
                      ? new Date(doc.createdAt).toLocaleString()
                      : "N/A"}
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td
                  colSpan="4"
                  className="px-6 py-4 text-center text-neutral-400"
                >
                  No documents available
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default Documents;
