'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 { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';

// Template component that accepts data
function OnboardingTemplate({ data }: { data: any }) {
  return <OnboardingWizard />;
}

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, error, refetch } = 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 (shouldRedirectToDashboard) {
    return null;
  }

  // For the StatefulPageWrapper, we need to provide data even if it's empty
  // The page is workflow-driven, not data-driven
  const wrapperData = driver || {};

  return (
    <main className="min-h-screen bg-deep-graphite">
      <StatefulPageWrapper
        data={wrapperData}
        isLoading={isLoading}
        error={error}
        retry={refetch}
        Template={OnboardingTemplate}
        loading={{ variant: 'full-screen', message: 'Loading onboarding...' }}
      />
    </main>
  );
}