import React, { useMemo, useState } from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { usePostHog } from 'posthog-react-native';
import { ThemeBackdrop } from '../../components/ThemeBackdrop';
import { useColors } from '../../constants/Colors';
import { useApp } from '../../context/AppContext';
import { OnboardingProgressService } from '../../services/onboardingProgressService';

const GOAL_OPTIONS = [
  { id: 'identify', icon: 'scan-outline' as const },
  { id: 'care', icon: 'water-outline' as const },
  { id: 'collection', icon: 'albums-outline' as const },
  { id: 'learn', icon: 'book-outline' as const },
];

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

  const goalLabels = useMemo(
    () => ({
      identify: t.goalOptionIdentify,
      care: t.goalOptionCare,
      collection: t.goalOptionCollection,
      learn: t.goalOptionLearn,
    }),
    [t.goalOptionCare, t.goalOptionCollection, t.goalOptionIdentify, t.goalOptionLearn],
  );

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

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

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <ThemeBackdrop colors={colors} />
      <SafeAreaView style={styles.safeArea} edges={['top', 'left', 'right', 'bottom']}>
        <View style={styles.header}>
          <View style={[styles.headerIcon, { backgroundColor: colors.primarySoft }]}>
            <Ionicons name="flag-outline" size={26} color={colors.primaryDark} />
          </View>
          <Text style={[styles.title, { color: colors.text }]}>{t.goalOnboardingTitle}</Text>
          <Text style={[styles.subtitle, { color: colors.textSecondary }]}>{t.goalOnboardingSubtitle}</Text>
        </View>

        <View style={styles.options}>
          {GOAL_OPTIONS.map((option) => {
            const isActive = selectedGoal === option.id;
            return (
              <TouchableOpacity
                key={option.id}
                style={[
                  styles.optionCard,
                  {
                    backgroundColor: isActive ? colors.primarySoft : colors.surface,
                    borderColor: isActive ? colors.primary : colors.border,
                  },
                ]}
                onPress={() => setSelectedGoal(option.id)}
                activeOpacity={0.85}
              >
                <View style={[styles.optionIcon, { backgroundColor: isActive ? colors.primary : colors.surfaceMuted }]}>
                  <Ionicons name={option.icon} size={18} color={isActive ? colors.onPrimary : colors.textMuted} />
                </View>
                <Text style={[styles.optionLabel, { color: colors.text }]}>{goalLabels[option.id as keyof typeof goalLabels]}</Text>
                {isActive && <Ionicons name="checkmark-circle" size={18} color={colors.primary} />}
              </TouchableOpacity>
            );
          })}
        </View>

        <View style={styles.footer}>
          <TouchableOpacity
            style={[styles.secondaryBtn, { borderColor: colors.borderStrong, backgroundColor: colors.surface }]}
            onPress={() => finish(null)}
          >
            <Text style={[styles.secondaryBtnText, { color: colors.text }]}>{t.goalOnboardingSkip}</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.primaryBtn, { backgroundColor: selectedGoal ? colors.primary : colors.surfaceMuted }]}
            onPress={() => finish(selectedGoal)}
            disabled={!selectedGoal}
          >
            <Text style={[styles.primaryBtnText, { color: selectedGoal ? colors.onPrimary : colors.textMuted }]}>
              {t.goalOnboardingContinue}
            </Text>
          </TouchableOpacity>
        </View>
      </SafeAreaView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  safeArea: { flex: 1, paddingHorizontal: 20, paddingTop: 24, paddingBottom: 20 },
  header: { alignItems: 'center', gap: 10, marginBottom: 28 },
  headerIcon: { width: 64, height: 64, borderRadius: 32, alignItems: 'center', justifyContent: 'center' },
  title: { fontSize: 28, fontWeight: '800', textAlign: 'center', lineHeight: 32 },
  subtitle: { fontSize: 14, textAlign: 'center', lineHeight: 20, maxWidth: 320 },
  options: { gap: 12, flex: 1 },
  optionCard: {
    minHeight: 64,
    borderRadius: 18,
    borderWidth: 1.5,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    gap: 12,
  },
  optionIcon: { width: 36, height: 36, borderRadius: 18, alignItems: 'center', justifyContent: 'center' },
  optionLabel: { flex: 1, fontSize: 15, fontWeight: '600' },
  footer: { flexDirection: 'row', gap: 12, marginTop: 16 },
  secondaryBtn: { flex: 1, height: 52, borderRadius: 16, borderWidth: 1.5, alignItems: 'center', justifyContent: 'center' },
  secondaryBtnText: { fontSize: 15, fontWeight: '600' },
  primaryBtn: { flex: 1.2, height: 52, borderRadius: 16, alignItems: 'center', justifyContent: 'center' },
  primaryBtnText: { fontSize: 15, fontWeight: '700' },
});
