"use client";

import { Box, Typography } from "@mui/material";
import { usePermissions } from "@/lib/hooks/usePermissions";
import { useEffect, useState } from "react";

function WithPermission({ children, permission_name }) {
  const { data, isLoading } = usePermissions();
  const [cachedData, setCachedData] = useState(null);

  useEffect(() => {
    if (data) {
      setCachedData(data);
    }
  }, [data]);

  if (isLoading || !cachedData || !permission_name) {
    return null;
  }

  const hasPermission =
    permission_name.includes("all") ||
    permission_name.some((permission) => cachedData.includes(permission));

  if (!hasPermission) {
    return (
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          height: "100%",
        }}
      >
        <Typography
          variant="h5"
          sx={{ letterSpacing: "2px", color: "error.main" }}
        >
          شما دسترسی لازم به این صفحه را ندارید
        </Typography>
      </Box>
    );
  }
  return <>{children}</>;
}

export default WithPermission;
