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 SOURCE_OPTIONS = [
  { id: 'app_store', emoji: '🏬', signal: 'organic_store' },
  { id: 'instagram', emoji: '📸', signal: 'social_visual' },
  { id: 'tiktok', emoji: '🎵', signal: 'social_video' },
  { id: 'friend', emoji: '👥', signal: 'referral' },
  { id: 'search', emoji: '🔎', signal: 'high_intent_search' },
  { id: 'other', emoji: '✨', signal: 'unclassified' },
];

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

  const sourceLabels: Record<string, string> = {
    app_store: t.sourceOptionAppStore,
    instagram: t.sourceOptionInstagram,
    tiktok: t.sourceOptionTikTok,
    friend: t.sourceOptionFriend,
    search: t.sourceOptionSearch,
    other: t.sourceOptionOther,
  };

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

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

    posthog.capture('onboarding_source_completed', {
      source: source ?? 'skipped',
      revops_signal: SOURCE_OPTIONS.find((option) => option.id === source)?.signal ?? 'skipped',
    });
    router.replace('/onboarding/goal');
  };

  return (
    <OnboardingQuestion
      colors={colors}
      isDarkMode={isDarkMode}
      step={1}
      totalSteps={4}
      title={t.sourceOnboardingTitle}
      subtitle={t.sourceOnboardingSubtitle}
      options={options}
      selectedId={selectedSource}
      onSelect={setSelectedSource}
      onContinue={() => finish(selectedSource)}
      onBack={() => router.back()}
      continueLabel={t.sourceOnboardingContinue}
      skipLabel={t.sourceOnboardingSkip}
      onSkip={() => finish(null)}
    />
  );
}
