import { useEffect, useState } from "react";
import { getAllUsers, updateRole } from "../api/users";
import StoreManagement from "../components/admin/StoreManagement";
import UserRoleCard from "../components/common/UserRoleCard";
import "../styles/UserRoleCard.css";
import "../styles/pages/AdminPanel.css";

export default function AdminPanel() {
  const [users, setUsers] = useState([]);
  const [activeTab, setActiveTab] = useState("users");

  async function loadUsers() {
    const allUsers = await getAllUsers();
    console.log("Users found:", users);
    setUsers(allUsers.data);
  }

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

  const changeRole = async (id, role) => {
    const updated = await updateRole(id, role);
    if (updated.status !== 200) return;
    loadUsers();
  }

  return (
    <div className="admin-panel-body">
      <div className="admin-panel-container">
        <h1 className="admin-panel-title">Admin Panel</h1>

        <div className="admin-tabs">
          <button
            className={`admin-tab ${activeTab === "users" ? "active" : ""}`}
            onClick={() => setActiveTab("users")}
          >
            User Management
          </button>
          <button
            className={`admin-tab ${activeTab === "stores" ? "active" : ""}`}
            onClick={() => setActiveTab("stores")}
          >
            Store Management
          </button>
        </div>

        <div className="admin-content">
          {activeTab === "users" && (
            <div className="users-section">
              {users.map((user) => (
                <UserRoleCard
                  key={user.id}
                  user={user}
                  onRoleChange={changeRole}
                />
              ))}
            </div>
          )}

          {activeTab === "stores" && <StoreManagement />}
        </div>
      </div>
    </div>
  )
}