import { useState, useEffect } from 'react';
import { getAllUsers, getAllDocuments, getUserInfo, createUser } from '../../services/api';
import DocumentUpload from '../documentUpload/DocumentUpload';
import { useNavigate } from 'react-router-dom';
import { FiUsers, FiFile, FiUpload, FiUserPlus, FiLoader } from 'react-icons/fi';

function AdminPanel() {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('documents');
  const [users, setUsers] = useState([]);
  const [documents, setDocuments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [isAdmin, setIsAdmin] = useState(false);
  const [newUser, setNewUser] = useState({
    name: '',
    email: '',
    password: '',
    isAdmin: false
  });

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

  useEffect(() => {
    if (isAdmin) {
      fetchData();
    }
  }, [activeTab, isAdmin]);

  const checkAdminStatus = async () => {
    try {
      const response = await getUserInfo();
      if (!response?.data?.isAdmin) {
        navigate('/');
      } else {
        setIsAdmin(true);
        await fetchData();
      }
    } catch (error) {
      console.error('Admin check failed:', error);
      navigate('/');
    }
  };

  const fetchData = async () => {
    setLoading(true);
    setError('');
    try {
      if (activeTab === 'users') {
        const response = await getAllUsers();
        setUsers(response.data);
      } else if (activeTab === 'documents') {
        const response = await getAllDocuments();
        console.log('Documents data:', response.data);
        setDocuments(response.data);
      }
    } catch (err) {
      console.error('Fetch error:', err);
      setError('Failed to fetch data. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleCreateUser = async (e) => {
    e.preventDefault();
    try {
      await createUser(newUser);
      setNewUser({
        name: '',
        email: '',
        password: '',
        isAdmin: false
      });
      fetchData();
    } catch (err) {
      setError('Failed to create user');
    }
  };

  if (!isAdmin) return null;

  const tabs = [
    { id: 'documents', name: 'Documents', icon: FiFile },
    { id: 'users', name: 'Users', icon: FiUsers },
    { id: 'upload', name: 'Upload Document', icon: FiUpload }
  ];

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-900">
        <div className="flex items-center space-x-3 text-blue-500">
          <FiLoader className="w-6 h-6 animate-spin" />
          <span className="text-lg font-medium">Loading...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-900 to-gray-800 p-6">
      <div className="max-w-7xl mx-auto">
        <header className="mb-8 mt-20">
          <h1 className="text-3xl font-bold text-white mb-2">Admin Dashboard</h1>
          <p className="text-gray-400">Manage users and documents</p>
        </header>

        {/* Tabs */}
        <div className="flex space-x-4 mb-6">
          {tabs.map(({ id, name, icon: Icon }) => (
            <button
              key={id}
              onClick={() => setActiveTab(id)}
              className={`
                px-4 py-2 rounded-lg flex items-center space-x-2 transition-colors
                ${activeTab === id 
                  ? 'bg-white/10 text-white' 
                  : 'text-gray-400 hover:bg-white/5 hover:text-white'}
              `}
            >
              <Icon className="w-4 h-4" />
              <span>{name}</span>
            </button>
          ))}
        </div>

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

        <div className="grid gap-6">
          {activeTab === 'documents' && (
            <div className="bg-white/5 backdrop-blur-lg rounded-xl overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b border-gray-700">
                      <th className="px-6 py-4 text-left text-sm text-gray-400">Title</th>
                      <th className="px-6 py-4 text-left text-sm text-gray-400">Status</th>
                      <th className="px-6 py-4 text-left text-sm text-gray-400">Uploaded By</th>
                      <th className="px-6 py-4 text-left text-sm text-gray-400">Shared With</th>
                      <th className="px-6 py-4 text-left text-sm text-gray-400">Created At</th>
                    </tr>
                  </thead>
                  <tbody>
                    {documents.map((doc) => (
                      <tr key={doc.id} className="border-b border-gray-700/50 hover:bg-white/5">
                        <td className="px-6 py-4 text-gray-200">{doc.title}</td>
                        <td className="px-6 py-4">
                          <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                            doc.status === 'completed' ? 'bg-green-500/10 text-green-400' :
                            doc.status === 'pending' ? 'bg-yellow-500/10 text-yellow-400' :
                            doc.status === 'uploading' ? 'bg-blue-500/10 text-blue-400' :
                            'bg-gray-500/10 text-gray-400'
                          }`}>
                            {doc.status}
                          </span>
                        </td>
                        <td className="px-6 py-4 text-gray-400">
                          {doc.uploadedBy?.name} ({doc.uploadedBy?.email})
                        </td>
                        <td className="px-6 py-4 text-gray-400">
                          {doc.sharedWith && doc.sharedWith.length > 0 
                            ? doc.sharedWith.map(user => (
                                <div key={user.id} className="whitespace-nowrap">
                                  {user.name} ({user.email})
                                </div>
                              ))
                            : 'None'}
                        </td>
                        <td className="px-6 py-4 text-gray-400">
                          {new Date(doc.createdAt).toLocaleString()}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {activeTab === 'users' && (
            <>
              <div className="bg-white/5 backdrop-blur-lg rounded-xl p-6 mb-6">
                <h2 className="text-xl font-bold text-white mb-4">Create New User</h2>
                <form onSubmit={handleCreateUser} className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  <input
                    type="text"
                    placeholder="Name"
                    value={newUser.name}
                    onChange={(e) => setNewUser({ ...newUser, name: e.target.value })}
                    className="bg-white/5 border border-gray-700 rounded-lg px-4 py-2 text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                    required
                  />
                  <input
                    type="email"
                    placeholder="Email"
                    value={newUser.email}
                    onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
                    className="bg-white/5 border border-gray-700 rounded-lg px-4 py-2 text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                    required
                  />
                  <input
                    type="password"
                    placeholder="Password"
                    value={newUser.password}
                    onChange={(e) => setNewUser({ ...newUser, password: e.target.value })}
                    className="bg-white/5 border border-gray-700 rounded-lg px-4 py-2 text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                    required
                  />
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="isAdmin"
                      checked={newUser.isAdmin}
                      onChange={(e) => setNewUser({ ...newUser, isAdmin: e.target.checked })}
                      className="rounded border-gray-700 bg-white/5 text-blue-500 focus:ring-blue-500"
                    />
                    <label htmlFor="isAdmin" className="text-gray-200">Is Admin</label>
                  </div>
                  <button
                    type="submit"
                    className="flex items-center justify-center space-x-2 px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors"
                  >
                    <FiUserPlus className="w-4 h-4" />
                    <span>Create User</span>
                  </button>
                </form>
              </div>

              <div className="bg-white/5 backdrop-blur-lg rounded-xl overflow-hidden">
                <table className="w-full">
                  <thead>
                    <tr className="border-b border-gray-700">
                      <th className="px-6 py-4 text-left text-sm text-gray-400">Name</th>
                      <th className="px-6 py-4 text-left text-sm text-gray-400">Email</th>
                      <th className="px-6 py-4 text-left text-sm text-gray-400">Role</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.map((user) => (
                      <tr key={user.id} className="border-b border-gray-700/50 hover:bg-white/5">
                        <td className="px-6 py-4 text-gray-200">{user.name}</td>
                        <td className="px-6 py-4 text-gray-200">{user.email}</td>
                        <td className="px-6 py-4">
                          <span className={`px-3 py-1 rounded-full text-xs font-medium
                            ${user.isAdmin ? 'bg-purple-500/10 text-purple-400' : 'bg-gray-500/10 text-gray-400'}`}>
                            {user.isAdmin ? 'Admin' : 'User'}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </>
          )}

          {activeTab === 'upload' && (
            <div className="bg-white/5 backdrop-blur-lg rounded-xl p-6">
              <DocumentUpload />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default AdminPanel;