'use client';

import { ReactNode, use, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAppSelector } from '@/store/hooks';
import { ROLE_PERMISSIONS, type Permission } from '@/constants/permissions';
import type { Role } from './authSlice';

/** Hook: current user's authorization state, for imperative checks (e.g. hide a button). */
// export function useAuthorization() {
//   const { authenticated, role, permissions, user } = useAppSelector((s) => s.auth);
//   console.log("AUTH:", authenticated, role, permissions, user)

//   const hasPermission = (perm: Permission | Permission[]) => {
//     const required = Array.isArray(perm) ? perm : [perm];
//     return required.every((p) => permissions.includes(p));
//   };

//   const hasAnyPermission = (perm: Permission[]) =>
//     perm.some((p) => permissions.includes(p));

//   const hasRole = (allowed: Role | Role[]) => {
//     const list = Array.isArray(allowed) ? allowed : [allowed];
//     return !!role && list.includes(role);
//   };

//   return { authenticated, role, permissions, user, hasPermission, hasAnyPermission, hasRole };
// }

export function useAuthorization() {
  const { authenticated, role, permissions: statePermissions, user } = useAppSelector((s) => s.auth);
  
  // FALLBACK: If the backend didn't supply an array of strings, use your local map
  const permissions = Array.isArray(statePermissions) && statePermissions.length > 0
    ? statePermissions 
    : (role ? ROLE_PERMISSIONS[role] || [] : []);

  const hasPermission = (perm: Permission | Permission[]) => {
    const required = Array.isArray(perm) ? perm : [perm];
    return required.every((p) => permissions.includes(p));
  };

  const hasAnyPermission = (perm: Permission[]) =>
    perm.some((p) => permissions.includes(p));

  const hasRole = (allowed: Role | Role[]) => {
    const list = Array.isArray(allowed) ? allowed : [allowed];
    return !!role && list.includes(role);
  };

  return { authenticated, role, permissions, user, hasPermission, hasAnyPermission, hasRole };
}

/** Renders children only if the user holds ALL given permissions. Otherwise renders `fallback`. */
export function PermissionGuard({
  permission,
  fallback = null,
  children,
}: {
  permission: Permission | Permission[];
  fallback?: ReactNode;
  children: ReactNode;
}) {
  const { hasPermission } = useAuthorization();
  return hasPermission(permission) ? <>{children}</> : <>{fallback}</>;
}

/** Renders children only if the user holds one of the given roles. Otherwise renders `fallback`. */
export function RoleGuard({
  role,
  fallback = null,
  children,
}: {
  role: Role | Role[];
  fallback?: ReactNode;
  children: ReactNode;
}) {
  const { hasRole } = useAuthorization();
  return hasRole(role) ? <>{children}</> : <>{fallback}</>;
}

/**
 * Client-side redirect guard for page-level protection, complementing the
 * server-side check in middleware.ts (defense in depth, not a substitute).
 */
export function ProtectedRoute({
  permission,
  role,
  children,
}: {
  permission?: Permission | Permission[];
  role?: Role | Role[];
  children: ReactNode;
}) {
  const router = useRouter();
  const { authenticated, hasPermission, hasRole } = useAuthorization();

  const authorized =
    authenticated &&
    (!permission || hasPermission(permission)) &&
    (!role || hasRole(role));

  useEffect(() => {
    if (!authenticated) {
      router.replace('/signin');
    } else if (!authorized) {
      router.replace('/forbidden');
    }
  }, [authenticated, authorized, router]);

  if (!authorized) return null;
  return <>{children}</>;
}
