"use client";

import { AuthGuard } from "@/components/AuthGuard";
import { useMe } from "@/hooks/useMe";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { LoadingState, ErrorState } from "@/components/ds";
import { BeautyPortalShell } from "@/modules/beauty/components/BeautyPortalShell";
import type { BeautyPortalId } from "@/modules/beauty/constants/portals";

function PortalGate({
  children,
  portalId,
}: {
  children: React.ReactNode;
  portalId: BeautyPortalId;
}) {
  const { me, loading, error, reload } = useMe();
  const router = useRouter();

  useEffect(() => {
    if (loading) return;
    if (me?.onboarding_required) router.replace("/onboarding");
  }, [me, loading, router]);

  if (loading) return <LoadingState label="در حال آماده‌سازی پورتال زیبایی…" />;
  if (error) return <ErrorState message={error} onRetry={reload} />;
  if (!me?.current_tenant_id) {
    return <ErrorState message="برای استفاده از تربت بیوتی باید workspace فعال داشته باشید." />;
  }

  return <BeautyPortalShell portalId={portalId}>{children}</BeautyPortalShell>;
}

export function createPortalLayout(portalId: BeautyPortalId) {
  return function PortalLayout({ children }: { children: React.ReactNode }) {
    return (
      <AuthGuard>
        <PortalGate portalId={portalId}>{children}</PortalGate>
      </AuthGuard>
    );
  };
}
