"use client";

import React, { useEffect } from "react";
import { useRouter, usePathname } from "next/navigation";
import Image from "next/image";
import { useAuth } from "@/context/AuthContext";
import { brandConfig } from "@/config/brand";
import { canAccessRoute } from "@/lib/rbac";
import { getRoleRedirectPath } from "@/lib/authTypes";

interface AuthGuardProps {
  children: React.ReactNode;
}

export const AuthGuard: React.FC<AuthGuardProps> = ({ children }) => {
  const { user, isAuthenticated, isLoading } = useAuth();
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      // Simpan returnUrl jika ingin kembali ke halaman yang dituju
      const redirectQuery = pathname && pathname !== "/" ? `?returnUrl=${encodeURIComponent(pathname)}` : "";
      router.replace(`/login${redirectQuery}`);
      return;
    }

    if (!isLoading && isAuthenticated && user) {
      if (!canAccessRoute(pathname, user.role)) {
        const redirectUrl = getRoleRedirectPath(user.role);
        if (redirectUrl && redirectUrl !== pathname && redirectUrl !== `${pathname}/`) {
          router.replace(redirectUrl);
        }
      }
    }
  }, [isLoading, isAuthenticated, user, router, pathname]);

  // Tampilkan splash screen saat memverifikasi sesi
  if (isLoading) {
    return (
      <div className="min-h-screen bg-slate-50 flex flex-col items-center justify-center p-4">
        <div className="flex flex-col items-center gap-4 text-center max-w-sm">
          <div className="relative w-16 h-16 sm:w-20 sm:h-20 animate-bounce duration-1000">
            <Image
              src={brandConfig.logo.src}
              alt={brandConfig.logo.alt}
              fill
              className="object-contain"
              priority
            />
          </div>

          <div className="space-y-1">
            <h2 className="text-base sm:text-lg font-bold text-brand-navy">
              {brandConfig.appName}
            </h2>
            <p className="text-xs text-slate-500">
              Memverifikasi sesi & hak akses {brandConfig.shortSchoolName}...
            </p>
          </div>

          <div className="w-48 h-1.5 bg-slate-200 rounded-full overflow-hidden mt-2">
            <div className="w-full h-full bg-blue-600 rounded-full animate-indeterminate" />
          </div>
        </div>
      </div>
    );
  }

  // Jika belum login atau rute tidak diizinkan
  if (!isAuthenticated || !user) {
    return null;
  }

  if (!canAccessRoute(pathname, user.role)) {
    return null;
  }

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