"use client";

import { AuthGuard } from "@/components/AuthGuard";
import { useMe } from "@/hooks/useMe";
import { useRouter, usePathname } from "next/navigation";
import { useEffect } from "react";
import { LoadingState, ErrorState } from "@/components/ds";
import { DeliveryPortalShell } from "@/modules/delivery/components/DeliveryPortalShell";

export type DeliveryPortalId = "operations";

function PortalGate({ children }: { children: React.ReactNode }) {
  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 <DeliveryPortalShell>{children}</DeliveryPortalShell>;
}

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

export function DeliveryRootLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const isHub = pathname === "/delivery/hub";

  if (isHub) {
    return <AuthGuard>{children}</AuthGuard>;
  }

  return (
    <AuthGuard>
      <PortalGate>{children}</PortalGate>
    </AuthGuard>
  );
}
