import React from 'react';
import { View, TouchableOpacity, StyleSheet } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { colors, spacing, radii, shadows } from '../../theme/tokens';
import { SafeScreen } from '../../components/layout/SafeScreen';
import { H2, Body, BodyMedium } from '../../components/ui';
import { useAppStore } from '../../store';
import { LOCALE_LABELS, t } from '../../i18n';
import type { SupportedLocale } from '../../types';

interface LanguageScreenProps {
  onNext: () => void;
}

const LANGUAGES: { code: SupportedLocale; flag: string }[] = [
  { code: 'fr', flag: '🇫🇷' },
  { code: 'en', flag: '🇬🇧' },
  { code: 'ar', flag: '🇸🇦' },
];

export function LanguageScreen({ onNext }: LanguageScreenProps) {
  const { locale, changeLocale } = useAppStore();

  const handleSelect = (code: SupportedLocale) => {
    changeLocale(code);
    setTimeout(onNext, 300);
  };

  return (
    <SafeScreen>
      <View style={styles.content}>
        <H2 align="center" style={styles.title}>
          {t('onboarding.chooseLanguage')}
        </H2>

        <View style={styles.list}>
          {LANGUAGES.map(({ code, flag }) => {
            const selected = locale === code;
            return (
              <TouchableOpacity
                key={code}
                style={[styles.option, selected && styles.optionSelected]}
                onPress={() => handleSelect(code)}
                accessibilityRole="radio"
                accessibilityState={{ selected }}
                accessibilityLabel={LOCALE_LABELS[code]}
              >
                <Body style={styles.flag}>{flag}</Body>
                <BodyMedium
                  style={[styles.label, selected && styles.labelSelected]}
                >
                  {LOCALE_LABELS[code]}
                </BodyMedium>
                {selected && (
                  <Ionicons
                    name="checkmark-circle"
                    size={24}
                    color={colors.primary[500]}
                    style={styles.check}
                  />
                )}
              </TouchableOpacity>
            );
          })}
        </View>
      </View>
    </SafeScreen>
  );
}

const styles = StyleSheet.create({
  content: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: spacing.xl,
  },
  title: {
    marginBottom: spacing['4xl'],
  },
  list: {
    gap: spacing.md,
  },
  option: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: spacing.xl,
    borderRadius: radii['2xl'],
    backgroundColor: colors.surface,
    borderWidth: 2,
    borderColor: 'transparent',
    ...shadows.sm,
  },
  optionSelected: {
    borderColor: colors.primary[500],
    backgroundColor: colors.primary[50],
  },
  flag: {
    fontSize: 28,
    marginRight: spacing.lg,
  },
  label: {
    flex: 1,
    fontSize: 17,
  },
  labelSelected: {
    color: colors.primary[700],
  },
  check: {
    marginLeft: spacing.sm,
  },
});
