import React, { useState } from 'react';
import { useRouter } from 'expo-router';
import { useSafeAnalytics } from '../../services/analytics';
import { useColors } from '../../constants/Colors';
import { useApp } from '../../context/AppContext';
import { OnboardingProgressService } from '../../services/onboardingProgressService';
import { PreAuthOnboardingService } from '../../services/preAuthOnboardingService';
import { OnboardingQuestion, QuestionOption } from '../../components/OnboardingQuestion';

const GOAL_OPTIONS = [
  { id: 'identify', emoji: '🔍' },
  { id: 'care', emoji: '💧' },
  { id: 'collection', emoji: '🗂️' },
  { id: 'learn', emoji: '📚' },
];

export default function OnboardingGoalScreen() {
  const router = useRouter();
  const posthog = useSafeAnalytics();
  const { session, isDarkMode, colorPalette, t } = useApp();
  const colors = useColors(isDarkMode, colorPalette);
  const [selectedGoal, setSelectedGoal] = useState<string | null>(null);

  const goalLabels: Record<string, string> = {
    identify: t.goalOptionIdentify,
    care: t.goalOptionCare,
    collection: t.goalOptionCollection,
    learn: t.goalOptionLearn,
  };

  const options: QuestionOption[] = GOAL_OPTIONS.map((option) => ({
    id: option.id,
    emoji: option.emoji,
    label: goalLabels[option.id],
  }));

  const finish = (goal: string | null) => {
    if (session?.userId && goal) {
      OnboardingProgressService.setPrimaryGoal(session.userId, goal);
    }
    if (goal) {
      void PreAuthOnboardingService.setAnswer('primaryGoal', goal);
    }

    posthog.capture('onboarding_goal_completed', {
      goal: goal ?? 'skipped',
    });
    router.replace('/onboarding/experience');
  };

  return (
    <OnboardingQuestion
      colors={colors}
      isDarkMode={isDarkMode}
      step={2}
      totalSteps={4}
      title={t.goalOnboardingTitle}
      subtitle={t.goalOnboardingSubtitle}
      options={options}
      selectedId={selectedGoal}
      onSelect={setSelectedGoal}
      onContinue={() => finish(selectedGoal)}
      onBack={() => router.back()}
      continueLabel={t.goalOnboardingContinue}
      skipLabel={t.goalOnboardingSkip}
      onSkip={() => finish(null)}
    />
  );
}
