"use client";

import type { ReactNode } from "react";
import { usePathname } from "next/navigation";
import { useDashboardAccess } from "@/hooks/use-dashboard-access";
import { canAccessDashboardRoute } from "@/lib/dashboard-permissions";
import Image from "next/image";
import pageNotFoundImg from '../../../public/assets/dashboard/page-not-found/404.png'

export function DashboardRouteGuard({ children }: { children: ReactNode }) {
  const pathname = usePathname();
  const { user, isLoading, isError, error } = useDashboardAccess();

  if (isLoading) {
    return (
      <div
        role="status"
        aria-live="polite"
        aria-label="Checking your access"
        className="space-y-4"
      >
        <ShimmerBlock className="h-7 w-48 rounded-md" />
        <ShimmerBlock className="h-4 w-72 rounded" />
        <span className="sr-only">Checking your access...</span>
      </div>
    );
  }

  if (isError) {
    return (
      <div
        role="alert"
        className="rounded-xl border border-amber-200 bg-amber-50 p-6 text-sm text-amber-800"
      >
        Your permissions could not be verified
        {error instanceof Error ? `: ${error.message}` : "."} Please refresh
        the page or contact an administrator.
      </div>
    );
  }

  if (!canAccessDashboardRoute(pathname, user)) {
    return (
      <div
        role="alert"
        className="rounded-xl border border-red-200 bg-red-50 p-6 text-sm text-red-700"
      >
        You do not have permission to access this page.
        <Image src={pageNotFoundImg.src} alt="" width={200} height={200}></Image>
      </div>
    );
  }

  return children;
}


function ShimmerBlock({ className = "" }: { className?: string }) {
  return (
    <div
      aria-hidden="true"
      className={`relative overflow-hidden bg-slate-200/70 ${className}`}
    >
      <div className="absolute inset-0 -translate-x-full animate-[shimmer_1.6s_infinite] bg-gradient-to-r from-transparent via-white/70 to-transparent" />
    </div>
  );
}