"use client";

import { useEffect, type ReactNode } from "react";
import { usePathname, useRouter } from "next/navigation";
import { ShieldX } from "lucide-react";
import { Button } from "@/components/ui/button";
import { EmptyState, ErrorState } from "@/components/shared/empty-state";
import { LoadingScreen } from "@/components/shared/loading";
import { useMe } from "@/hooks/use-auth";
import { getErrorMessage } from "@/lib/api";
import { findNavItem, homeForRole } from "@/lib/navigation";
import type { Role } from "@/types";

/** Pastikan user login; arahkan ke /login bila sesi tidak valid. */
export function AuthGuard({ children }: { children: ReactNode }) {
  const { data: user, isLoading, isError, error, refetch } = useMe();
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    if (!isLoading && user === null) {
      router.replace(`/login?next=${encodeURIComponent(pathname + window.location.search)}`);
    }
  }, [isLoading, user, router, pathname]);

  if (isError) return <ErrorState message={getErrorMessage(error)} onRetry={() => refetch()} />;
  if (isLoading || !user) return <LoadingScreen />;

  return <>{children}</>;
}

/** Tolak akses halaman bila peran user tidak terdaftar pada item navigasi untuk path ini. */
export function RouteRoleGate({ role, children }: { role: Role; children: ReactNode }) {
  const pathname = usePathname();
  const item = findNavItem(pathname);

  if (item && !item.roles.includes(role)) {
    return <Forbidden home={homeForRole(role)} />;
  }

  return <>{children}</>;
}

/** Proteksi eksplisit di level halaman / komponen. */
export function RoleGate({ allow, role, children, fallback }: { allow: Role[]; role: Role; children: ReactNode; fallback?: ReactNode }) {
  if (!allow.includes(role)) return <>{fallback ?? <Forbidden home={homeForRole(role)} />}</>;
  return <>{children}</>;
}

function Forbidden({ home }: { home: string }) {
  const router = useRouter();
  return (
    <EmptyState
      icon={<ShieldX className="h-6 w-6" />}
      title="Akses ditolak"
      description="Peran Anda tidak memiliki akses ke halaman ini."
      action={<Button onClick={() => router.replace(home)}>Kembali ke beranda</Button>}
    />
  );
}
