"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 "@/src/shared/ui";
import { HealthcarePortalShell } from "@/src/modules/healthcare/components/HealthcarePortalShell";
import type { HealthcarePortalId } from "@/src/modules/healthcare/constants/portals";

function PortalGate({
  children,
  portalId,
}: {
  children: React.ReactNode;
  portalId: HealthcarePortalId;
}) {
  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 <HealthcarePortalShell portalId={portalId}>{children}</HealthcarePortalShell>;
}

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