import React from 'react';
import { View, TouchableOpacity, StyleSheet, ScrollView } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { colors, spacing, radii, shadows } from '../../theme/tokens';
import { H2, Body, Button, Caption } from '../../components/ui';
import { t } from '../../i18n';
import { useQuizStore } from '../../store';
import type { HouseholdStatus, HousingType } from '../../types';

interface Props { onNext: () => void }

const STATUS_OPTIONS: { value: HouseholdStatus; labelKey: string }[] = [
  { value: 'married', labelKey: 'quiz.married' },
  { value: 'common_law', labelKey: 'quiz.commonLaw' },
  { value: 'cohabiting', labelKey: 'quiz.cohabiting' },
  { value: 'other', labelKey: 'quiz.other' },
];

const HOUSING_OPTIONS: { value: HousingType; labelKey: string }[] = [
  { value: 'rent', labelKey: 'quiz.rent' },
  { value: 'own_mortgage', labelKey: 'quiz.ownMortgage' },
  { value: 'own_paid', labelKey: 'quiz.ownPaid' },
  { value: 'other', labelKey: 'quiz.other' },
];

const OBJECTIVES = [
  { value: 'equity', labelKey: 'quiz.objEquity' },
  { value: 'savings', labelKey: 'quiz.objSavings' },
  { value: 'debt', labelKey: 'quiz.objDebt' },
  { value: 'project', labelKey: 'quiz.objProject' },
  { value: 'peace', labelKey: 'quiz.objPeace' },
];

function ChipSelect<T extends string>({
  options,
  selected,
  onSelect,
  multi = false,
  selectedMulti = [],
  onToggle,
}: {
  options: { value: T; labelKey: string }[];
  selected?: T | null;
  onSelect?: (v: T) => void;
  multi?: boolean;
  selectedMulti?: string[];
  onToggle?: (v: string) => void;
}) {
  return (
    <View style={styles.chipRow}>
      {options.map((opt) => {
        const isSelected = multi
          ? selectedMulti.includes(opt.value)
          : selected === opt.value;
        return (
          <TouchableOpacity
            key={opt.value}
            style={[styles.chip, isSelected && styles.chipSelected]}
            onPress={() => (multi ? onToggle?.(opt.value) : onSelect?.(opt.value))}
            accessibilityRole="radio"
            accessibilityState={{ selected: isSelected }}
          >
            <Body style={[styles.chipText, isSelected && styles.chipTextSelected]}>
              {t(opt.labelKey)}
            </Body>
          </TouchableOpacity>
        );
      })}
    </View>
  );
}

export function QuizStep1({ onNext }: Props) {
  const {
    householdStatus, setHouseholdStatus,
    children, setChildren,
    housingType, setHousingType,
    objectives, toggleObjective,
  } = useQuizStore();

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
      <H2>{t('quiz.step1Title')}</H2>
      <Body style={styles.subtitle} color={colors.neutral[500]}>
        {t('quiz.step1Subtitle')}
      </Body>

      <Caption style={styles.sectionLabel}>{t('quiz.maritalStatus')}</Caption>
      <ChipSelect
        options={STATUS_OPTIONS}
        selected={householdStatus}
        onSelect={setHouseholdStatus}
      />

      <Caption style={styles.sectionLabel}>{t('quiz.children')}</Caption>
      <View style={styles.counterRow}>
        <TouchableOpacity
          style={styles.counterBtn}
          onPress={() => setChildren(Math.max(0, children - 1))}
          accessibilityLabel="Decrease children"
        >
          <Ionicons name="remove" size={20} color={colors.neutral[600]} />
        </TouchableOpacity>
        <Body style={styles.counterValue}>{children}</Body>
        <TouchableOpacity
          style={styles.counterBtn}
          onPress={() => setChildren(children + 1)}
          accessibilityLabel="Increase children"
        >
          <Ionicons name="add" size={20} color={colors.neutral[600]} />
        </TouchableOpacity>
      </View>

      <Caption style={styles.sectionLabel}>{t('quiz.housingType')}</Caption>
      <ChipSelect
        options={HOUSING_OPTIONS}
        selected={housingType}
        onSelect={setHousingType}
      />

      <Caption style={styles.sectionLabel}>{t('quiz.objectives')}</Caption>
      <ChipSelect
        options={OBJECTIVES}
        multi
        selectedMulti={objectives}
        onToggle={toggleObjective}
      />

      <View style={styles.footer}>
        <Button title={t('common.next')} onPress={onNext} fullWidth size="lg" />
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  scrollContent: {
    paddingHorizontal: spacing.xl,
    paddingBottom: spacing['5xl'],
  },
  subtitle: { marginTop: spacing.xs, marginBottom: spacing['2xl'] },
  sectionLabel: {
    marginBottom: spacing.sm,
    marginTop: spacing.xl,
    textTransform: 'uppercase',
    letterSpacing: 1,
    color: colors.neutral[500],
  },
  chipRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing.sm,
  },
  chip: {
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.md,
    borderRadius: radii.full,
    backgroundColor: colors.surface,
    borderWidth: 1.5,
    borderColor: colors.neutral[200],
    ...shadows.sm,
  },
  chipSelected: {
    backgroundColor: colors.primary[50],
    borderColor: colors.primary[500],
  },
  chipText: {
    color: colors.neutral[700],
    fontSize: 14,
  },
  chipTextSelected: {
    color: colors.primary[700],
    fontWeight: '600',
  },
  counterRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xl,
  },
  counterBtn: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: colors.neutral[100],
    alignItems: 'center',
    justifyContent: 'center',
  },
  counterValue: {
    fontSize: 24,
    fontWeight: '700',
    minWidth: 32,
    textAlign: 'center',
  },
  footer: {
    marginTop: spacing['3xl'],
  },
});
