import { View, Text, Pressable, TextInput, StyleSheet } from 'react-native';
import { RhythmOption } from '../../../api/profile';
import { colors, spacing, radii, typography } from '../../../theme';

type Props = {
  options: RhythmOption[];
  value: string | null;
  rhythmTargets: Record<string, number>;
  customKcal: string;
  onSelect: (value: string) => void;
  onCustomKcalChange: (text: string) => void;
  disabled?: boolean;
};

export function RhythmSelector({ options, value, rhythmTargets, customKcal, onSelect, onCustomKcalChange, disabled }: Props) {
  return (
    <View style={styles.list}>
      {options.map((option) => {
        const selected = option.value === value;
        const isCustom = option.value === 'personnalise';
        const kcal = rhythmTargets[option.value];

        return (
          <Pressable
            key={option.value}
            style={[styles.card, selected && styles.cardSelected]}
            onPress={() => onSelect(option.value)}
            disabled={disabled}
          >
            <View style={styles.cardMain}>
              <Text style={styles.label}>{option.label}</Text>
              <Text style={styles.desc}>{option.description}</Text>
            </View>
            {isCustom ? (
              <TextInput
                style={styles.customInput}
                keyboardType="number-pad"
                placeholder="kcal / j"
                placeholderTextColor={colors.textMuted}
                value={customKcal}
                onFocus={() => onSelect('personnalise')}
                onChangeText={(text) => {
                  onSelect('personnalise');
                  onCustomKcalChange(text);
                }}
                editable={!disabled}
              />
            ) : (
              <Text style={styles.kcal}>{kcal ? `${kcal} kcal/j` : '—'}</Text>
            )}
          </Pressable>
        );
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  list: { gap: spacing.sm },
  card: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: spacing.sm,
    borderWidth: 2,
    borderColor: colors.border,
    borderRadius: radii.md,
    padding: spacing.md,
    backgroundColor: colors.card,
  },
  cardSelected: { borderColor: colors.primary, backgroundColor: '#f5f4ff' },
  cardMain: { flex: 1, gap: 2 },
  label: { ...typography.body, fontWeight: '700', color: colors.text },
  desc: { ...typography.caption, color: colors.textMuted },
  kcal: { fontSize: 14, fontWeight: '700', color: colors.text },
  customInput: {
    width: 90,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
    textAlign: 'right',
    color: colors.text,
    fontWeight: '700',
  },
});
