"use client";

import { Spin } from "antd";
import type { ReactNode } from "react";
import { Suspense, useEffect, useState } from "react";
import { useRouter } from "next/navigation";

import { AppLayout } from "@/components/layout/AppLayout";
import { PlatformBrandingProvider } from "@/lib/branding/platform-branding";
import { useAuth } from "@/lib/hooks/use-auth";
import { useAuthStore } from "@/store/auth-store";

function DashboardLayoutContent({ children }: { children: ReactNode }) {
  const router = useRouter();
  const { bootstrap } = useAuth();
  const [checking, setChecking] = useState(true);
  const user = useAuthStore((state) => state.user);
  const tokens = useAuthStore((state) => state.tokens);
  const hasSession = Boolean(user && tokens.accessToken && tokens.refreshToken);

  useEffect(() => {
    let cancelled = false;
    const verify = async () => {
      const session = await bootstrap();
      if (cancelled) return;
      if (session) {
        setChecking(false);
        return;
      }
      router.replace("/auth/login?reason=session_expired");
    };

    void verify();

    return () => {
      cancelled = true;
    };
  }, [bootstrap, router]);

  useEffect(() => {
    if (checking || hasSession) {
      return;
    }
    router.replace("/auth/login?reason=session_expired");
  }, [checking, hasSession, router]);

  if (checking) {
    return (
      <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <PlatformBrandingProvider setDocumentTitle>
      <AppLayout>{children}</AppLayout>
    </PlatformBrandingProvider>
  );
}

export default function DashboardLayout({ children }: { children: ReactNode }) {
  return (
    <Suspense
      fallback={
        <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Spin size="large" />
        </div>
      }
    >
      <DashboardLayoutContent>{children}</DashboardLayoutContent>
    </Suspense>
  );
}
