"use client";

import { jwtDecode } from "jwt-decode";
import React, { useEffect, useState } from "react";

const AdminOnly = ({ children }) => {
    const [userRole, setUserRole] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const token = localStorage.getItem("medication-auth-token");

    if (!token) {
        typeof window !== "undefined" && window.location.replace("/");
        return;
    }

    useEffect(() => {
        const decoded = jwtDecode(token);
        const { role } = decoded.payload;
        if (role !== "admin") {
            localStorage.removeItem("medication-auth-token");
            typeof window !== "undefined" && window.location.replace("/");
        }
        setUserRole(role);
        setIsLoading(false);
    }, [token]);


    if (isLoading) {
        return (
            <div className="flex items-center justify-center h-screen">
                Loading...
            </div>
        );
    }

    return <>{children}</>;
};

export default AdminOnly;
