'use client';

import { useRouter } from 'next/navigation';
import { OnboardingWizard } from '@/components/onboarding/OnboardingWizard';
import { routes } from '@/lib/routing/RouteConfig';
import { completeOnboardingAction } from './completeOnboardingAction';
import { generateAvatarsAction } from './generateAvatarsAction';
import { useAuth } from '@/lib/auth/AuthContext';

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

  const handleCompleteOnboarding = async (input: {
    firstName: string;
    lastName: string;
    displayName: string;
    country: string;
    timezone?: string;
  }) => {
    try {
      const result = await completeOnboardingAction(input);
      
      if (result.isErr()) {
        return { success: false, error: result.getError() };
      }
      
      router.push(routes.protected.dashboard);
      router.refresh();
      return { success: true };
    } catch (error) {
      return { success: false, error: 'Failed to complete onboarding' };
    }
  };

  const handleGenerateAvatars = async (params: {
    facePhotoData: string;
    suitColor: string;
  }) => {
    if (!session?.user?.userId) {
      return { success: false, error: 'Not authenticated' };
    }

    try {
      const result = await generateAvatarsAction({
        userId: session.user.userId,
        facePhotoData: params.facePhotoData,
        suitColor: params.suitColor,
      });

      if (result.isErr()) {
        return { success: false, error: result.getError() };
      }

      const data = result.unwrap();
      return { success: true, data };
    } catch (error) {
      return { success: false, error: 'Failed to generate avatars' };
    }
  };

  return (
    <OnboardingWizard
      onCompleted={() => {
        router.push(routes.protected.dashboard);
        router.refresh();
      }}
      onCompleteOnboarding={handleCompleteOnboarding}
      onGenerateAvatars={handleGenerateAvatars}
    />
  );
}