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 EXPERIENCE_OPTIONS = [
  { id: 'beginner', emoji: '🌱' },
  { id: 'intermediate', emoji: '☀️' },
  { id: 'advanced', emoji: '🧪' },
];

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

  const levelLabels: Record<string, string> = {
    beginner: t.experienceOptionBeginner,
    intermediate: t.experienceOptionIntermediate,
    advanced: t.experienceOptionAdvanced,
  };

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

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

    posthog.capture('onboarding_experience_completed', {
      experience_level: level ?? 'skipped',
    });
    router.replace('/onboarding/health-check');
  };

  return (
    <OnboardingQuestion
      colors={colors}
      isDarkMode={isDarkMode}
      step={3}
      totalSteps={4}
      title={t.experienceOnboardingTitle}
      subtitle={t.experienceOnboardingSubtitle}
      options={options}
      selectedId={selectedLevel}
      onSelect={setSelectedLevel}
      onContinue={() => finish(selectedLevel)}
      onBack={() => router.back()}
      continueLabel={t.experienceOnboardingContinue}
      skipLabel={t.experienceOnboardingSkip}
      onSkip={() => finish(null)}
    />
  );
}
