import { useState, useEffect } from 'react';
import { getAllUsers, getAllDocuments, getUserInfo, createUser, resetUserPassword } from '../../services/api';
import DocumentUpload from '../documentUpload/DocumentUpload';
import { useNavigate } from 'react-router-dom';
import { FiUsers, FiFile, FiUpload, FiUserPlus, FiLoader, FiKey } 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 [resetPasswordModal, setResetPasswordModal] = useState({
    isOpen: false,
    userId: null,
    userName: '',
    newPassword: '',
  });
  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');
    }
  };

  const handleResetPassword = async (e) => {
    e.preventDefault();
    try {
      await resetUserPassword(resetPasswordModal.userId, resetPasswordModal.newPassword);
      setResetPasswordModal({
        isOpen: false,
        userId: null,
        userName: '',
        newPassword: '',
      });
      // Show success message
      setError('Password reset successful');
      setTimeout(() => setError(''), 3000);
    } catch (err) {
      setError('Failed to reset password');
    }
  };

  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-primary-900">
        <div className="flex items-center space-x-3 text-primary-400">
          <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-primary-900 to-primary-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-neutral-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-primary-600 text-white' 
                  : 'text-neutral-400 hover:bg-primary-700/50 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>
        )}

        {resetPasswordModal.isOpen && (
          <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50">
            <div className="bg-primary-800 rounded-xl p-6 w-full max-w-md">
              <h3 className="text-xl font-bold text-white mb-4">
                Reset Password for {resetPasswordModal.userName}
              </h3>
              <form onSubmit={handleResetPassword} className="space-y-4">
                <input
                  type="password"
                  placeholder="New Password"
                  value={resetPasswordModal.newPassword}
                  onChange={(e) => setResetPasswordModal({
                    ...resetPasswordModal,
                    newPassword: e.target.value
                  })}
                  className="w-full bg-primary-700/30 border border-primary-600 rounded-lg px-4 py-2 
                  text-white placeholder-neutral-400 focus:outline-none focus:border-primary-500
                  focus:ring-1 focus:ring-primary-500"
                  required
                  minLength={6}
                />
                <div className="flex justify-end space-x-3">
                  <button
                    type="button"
                    onClick={() => setResetPasswordModal({
                      isOpen: false,
                      userId: null,
                      userName: '',
                      newPassword: '',
                    })}
                    className="px-4 py-2 text-neutral-400 hover:text-white transition-colors"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    className="flex items-center justify-center space-x-2 px-4 py-2 
                    bg-primary-600 hover:bg-primary-700 text-white rounded-lg 
                    transition-colors shadow-lg"
                  >
                    <FiKey className="w-4 h-4" />
                    <span>Reset Password</span>
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

        <div className="grid gap-6">
          {activeTab === 'documents' && (
            <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-sm text-neutral-400">Title</th>
                      <th className="px-6 py-4 text-left text-sm text-neutral-400">Status</th>
                      <th className="px-6 py-4 text-left text-sm text-neutral-400">Uploaded By</th>
                      <th className="px-6 py-4 text-left text-sm text-neutral-400">Shared With</th>
                      <th className="px-6 py-4 text-left text-sm text-neutral-400">Created At</th>
                    </tr>
                  </thead>
                  <tbody>
                    {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}</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/20 text-green-300' :
                            doc.status === 'pending' ? 'bg-yellow-500/20 text-yellow-300' :
                            doc.status === 'uploading' ? 'bg-primary-500/20 text-primary-300' :
                            'bg-neutral-500/20 text-neutral-300'
                          }`}>
                            {doc.status}
                          </span>
                        </td>
                        <td className="px-6 py-4 text-neutral-300">
                          {doc.uploadedBy?.name} ({doc.uploadedBy?.email})
                        </td>
                        <td className="px-6 py-4 text-neutral-300">
                          {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-neutral-300">
                          {new Date(doc.createdAt).toLocaleString()}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {activeTab === 'users' && (
            <>
              <div className="bg-primary-800/50 backdrop-blur-lg rounded-xl p-6 mb-6 shadow-xl">
                <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-primary-700/30 border border-primary-600 rounded-lg px-4 py-2 
                    text-white placeholder-neutral-400 focus:outline-none focus:border-primary-500
                    focus:ring-1 focus:ring-primary-500"
                    required
                  />
                  <input
                    type="email"
                    placeholder="Email"
                    value={newUser.email}
                    onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
                    className="bg-primary-700/30 border border-primary-600 rounded-lg px-4 py-2 
                    text-white placeholder-neutral-400 focus:outline-none focus:border-primary-500
                    focus:ring-1 focus:ring-primary-500"
                    required
                  />
                  <input
                    type="password"
                    placeholder="Password"
                    value={newUser.password}
                    onChange={(e) => setNewUser({ ...newUser, password: e.target.value })}
                    className="bg-primary-700/30 border border-primary-600 rounded-lg px-4 py-2 
                    text-white placeholder-neutral-400 focus:outline-none focus:border-primary-500
                    focus:ring-1 focus:ring-primary-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-primary-600 bg-primary-700/30 text-primary-500 
                      focus:ring-primary-500"
                    />
                    <label htmlFor="isAdmin" className="text-white">Is Admin</label>
                  </div>
                  <button
                    type="submit"
                    className="flex items-center justify-center space-x-2 px-4 py-2 
                    bg-primary-600 hover:bg-primary-700 text-white rounded-lg 
                    transition-colors shadow-lg"
                  >
                    <FiUserPlus className="w-4 h-4" />
                    <span>Create User</span>
                  </button>
                </form>
              </div>

              <div className="bg-primary-800/50 backdrop-blur-lg rounded-xl overflow-hidden shadow-xl">
                <table className="w-full">
                  <thead>
                    <tr className="border-b border-primary-700">
                      <th className="px-6 py-4 text-left text-sm text-neutral-400">Name</th>
                      <th className="px-6 py-4 text-left text-sm text-neutral-400">Email</th>
                      <th className="px-6 py-4 text-left text-sm text-neutral-400">Role</th>
                      <th className="px-6 py-4 text-left text-sm text-neutral-400">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.map((user) => (
                      <tr key={user.id} className="border-b border-primary-700/50 hover:bg-primary-700/30">
                        <td className="px-6 py-4 text-white">{user.name}</td>
                        <td className="px-6 py-4 text-white">{user.email}</td>
                        <td className="px-6 py-4">
                          <span className={`px-3 py-1 rounded-full text-xs font-medium
                            ${user.isAdmin ? 'bg-primary-500/20 text-primary-300' : 'bg-neutral-500/20 text-neutral-300'}`}>
                            {user.isAdmin ? 'Admin' : 'User'}
                          </span>
                        </td>
                        <td className="px-6 py-4">
                          <button
                            onClick={() => setResetPasswordModal({
                              isOpen: true,
                              userId: user.id,
                              userName: user.name,
                              newPassword: '',
                            })}
                            className="flex items-center space-x-1 text-neutral-400 hover:text-white transition-colors"
                          >
                            <FiKey className="w-4 h-4" />
                            <span>Reset Password</span>
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </>
          )}

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

export default AdminPanel;