import { useState, useEffect } from "react";
import {
  getAllUsers,
  getAllDocuments,
  getUserInfo,
  createUser,
  resetUserPassword,
} from "../../services/api";
import DocumentUpload from "../documentUpload/DocumentUpload";
import Documents from "../documentUpload/Documents";
import { useNavigate } from "react-router-dom";
import { motion } from "framer-motion";
import {
  FiUsers,
  FiFile,
  FiUpload,
  FiUserPlus,
  FiLoader,
  FiKey,
} from "react-icons/fi";
import { useRef } from "react";

function AdminPanel() {
  const createUserFormRef = useRef(null);
  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);
      fetchData();
    } catch (err) {
      setError("Failed to create user");
    } finally {
      // setNewUser(initialUserFormState);
      setNewUser({
        name: "",
        email: "",
        password: "",
        isAdmin: false,
      });
    }
  };

  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: "Документи", icon: FiFile },
    { id: "users", name: "Клиенти", icon: FiUsers },
    { id: "upload", name: "Прикачи документ", 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">Клиенти и доументи</p>
        </header>
        {/* <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        > */}
        {/* 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">
                Ресетирај лозинка за корисникот
              </h3>
              <h3 className="text-xl font-bold text-white mb-4">
                {resetPasswordModal.userName}
              </h3>
              <form onSubmit={handleResetPassword} className="space-y-4">
                <input
                  type="password"
                  placeholder="Нова лозинка"
                  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"
                  >
                    Откажи
                  </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>Потврди</span>
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

        {/* <div className="grid gap-6"> */}
        <>
          {activeTab === "documents" && (
            <div className="bg-primary-800/50 backdrop-blur-lg rounded-xl p-6 shadow-xl">
              <Documents />
            </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">
                Креирај корисник
              </h2>
              <form
                ref={createUserFormRef}
                onSubmit={handleCreateUser}
                className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4"
              >
                <input
                  type="text"
                  placeholder="Име"
                  value={newUser.name}
                  id="name"
                  name="name"
                  required
                  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"
                />
                <input
                  type="email"
                  id="email"
                  name="email"
                  placeholder="Мејл"
                  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"
                  id="password"
                  name="password"
                  placeholder="Лозинка"
                  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">
                    Дали е Администратор
                  </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>Креирај корисник</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">
                      Име
                    </th>
                    <th className="px-6 py-4 text-left text-sm text-neutral-400">
                      Мејл
                    </th>
                    <th className="px-6 py-4 text-left text-sm text-neutral-400">
                      Улога
                    </th>
                    <th className="px-6 py-4 text-left text-sm text-neutral-400">
                      Ресетирај
                    </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>Ресетирај лозинка</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>
  );
}

export default AdminPanel;
