"use client";

import { useAuth } from "../../contexts/AuthContext";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import {
  hasRoutePermission,
  getUnauthorizedMessage,
  getDefaultRouteForRoles,
} from "../../config/routePermissions";

interface AutoRoleGuardProps {
  children: React.ReactNode;
}

export default function AutoRoleGuard({ children }: AutoRoleGuardProps) {
  const { user, isLoading: authLoading } = useAuth();
  const pathname = usePathname();
  const router = useRouter();
  const [isChecking, setIsChecking] = useState(true);
  const [hasAccess, setHasAccess] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string>("");

  useEffect(() => {
    // If authentication is still loading, keep checking state
    if (authLoading) {
      setIsChecking(true);
      return;
    }

    // If no user after loading is complete, redirect to login
    if (!user) {
      router.push("/login");
      return;
    }

    // Get user role keys with proper filtering
    const userRoles =
      user.roles
        ?.map((role) => role?.key)
        .filter((key): key is string => Boolean(key)) || [];

    // If user has no valid roles, wait a bit longer or redirect to login
    if (userRoles.length === 0 && user.roles && user.roles.length > 0) {
      // Roles exist but keys are undefined, wait a bit more
      setTimeout(() => {
        // Try again after a short delay
        const retryUserRoles =
          user.roles
            ?.map((role) => role?.key)
            .filter((key): key is string => Boolean(key)) || [];

        if (retryUserRoles.length === 0) {
          router.push("/login");
        }
      }, 500);
      return;
    }

    // Check if user has permission for current route
    const canAccess = hasRoutePermission(pathname, userRoles);

    if (canAccess) {
      setHasAccess(true);
      setErrorMessage("");
    } else {
      setHasAccess(false);
      setErrorMessage(getUnauthorizedMessage(pathname, userRoles));

      // Optionally redirect to a default route after a delay
      setTimeout(() => {
        const defaultRoute = getDefaultRouteForRoles(userRoles);
        router.push(defaultRoute);
      }, 3000);
    }

    setIsChecking(false);
  }, [user, authLoading, pathname, router]);

  // Show loading while authentication is loading or checking permissions
  if (authLoading || isChecking) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mr-3"></div>
        <span>Loading...</span>
      </div>
    );
  }

  // Show unauthorized message if no access
  if (!hasAccess) {
    return (
      <div className="flex flex-col justify-center items-center h-64 p-8">
        <div className="bg-red-50 border border-red-200 rounded-lg p-6 max-w-md text-center">
          <div className="flex justify-center mb-4">
            <svg
              className="w-12 h-12 text-red-500"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.5 0L4.268 16.5c-.77.833.192 2.5 1.732 2.5z"
              />
            </svg>
          </div>
          <h2 className="text-xl font-semibold text-red-800 mb-2">
            Access Denied
          </h2>
          <p className="text-red-600 mb-4">{errorMessage}</p>
          <p className="text-sm text-red-500">
            Redirecting to your dashboard in 3 seconds...
          </p>
        </div>
      </div>
    );
  }

  // Render children if user has access
  return <>{children}</>;
}
