'use client';

import { useRouter } from 'next/navigation';
import { useEffect } from 'react';

import OnboardingWizard from '@/components/onboarding/OnboardingWizard';
import { useAuth } from '@/lib/auth/AuthContext';

// Shared state components
import { useCurrentDriver } from '@/hooks/driver/useCurrentDriver';
import { LoadingWrapper } from '@/components/shared/state/LoadingWrapper';

export default function OnboardingPage() {
  const router = useRouter();
  const { session } = useAuth();

  // Check if user is logged in
  const shouldRedirectToLogin = !session;

  // Fetch current driver data using DI + React-Query
  const { data: driver, isLoading } = useCurrentDriver({
    enabled: !!session,
  });

  const shouldRedirectToDashboard = !isLoading && Boolean(driver);

  useEffect(() => {
    if (shouldRedirectToLogin) {
      router.replace('/auth/login?returnTo=/onboarding');
      return;
    }
    if (shouldRedirectToDashboard) {
      router.replace('/dashboard');
    }
  }, [router, shouldRedirectToLogin, shouldRedirectToDashboard]);

  if (shouldRedirectToLogin) {
    return null;
  }

  if (isLoading) {
    return (
      <main className="min-h-screen bg-deep-graphite">
        <LoadingWrapper variant="full-screen" message="Loading onboarding..." />
      </main>
    );
  }

  if (shouldRedirectToDashboard) {
    return null;
  }

  return (
    <main className="min-h-screen bg-deep-graphite">
      <OnboardingWizard />
    </main>
  );
}