import { View, Text, StyleSheet } from 'react-native';
import { FoodLookupItem } from '../../../api/foodLookup';
import { colors, spacing, radii, typography } from '../../../theme';

function macro(value: number | null, unit: string): string {
  return value === null ? '—' : `${value.toFixed(1)} ${unit}`;
}

export function FoodLookupItemCard({ item }: { item: FoodLookupItem }) {
  return (
    <View style={styles.card}>
      <View style={styles.head}>
        <Text style={styles.name} numberOfLines={2}>{item.label}</Text>
        <Text style={styles.refQty}>{item.referenceQty}</Text>
      </View>
      {item.meta ? <Text style={styles.meta}>{item.meta}</Text> : null}
      {Object.keys(item.refs).length > 0 ? (
        <Text style={styles.refs}>
          {Object.entries(item.refs).map(([label, value]) => `${label} ${value}`).join(' · ')}
        </Text>
      ) : null}
      <View style={styles.macros}>
        <View style={styles.macro}>
          <Text style={styles.macroValue}>{macro(item.macros.caloriesPer100, 'kcal')}</Text>
          <Text style={styles.macroLabel}>Kcal</Text>
        </View>
        <View style={styles.macro}>
          <Text style={styles.macroValue}>{macro(item.macros.proteinPer100, 'g')}</Text>
          <Text style={styles.macroLabel}>Protéines</Text>
        </View>
        <View style={styles.macro}>
          <Text style={styles.macroValue}>{macro(item.macros.carbsPer100, 'g')}</Text>
          <Text style={styles.macroLabel}>Glucides</Text>
        </View>
        <View style={styles.macro}>
          <Text style={styles.macroValue}>{macro(item.macros.fatPer100, 'g')}</Text>
          <Text style={styles.macroLabel}>Lipides</Text>
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  card: { borderWidth: 1, borderColor: colors.border, borderRadius: radii.md, padding: spacing.sm, gap: 4 },
  head: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: spacing.sm },
  name: { ...typography.body, fontSize: 14, fontWeight: '700', color: colors.text, flex: 1 },
  refQty: { ...typography.caption, fontSize: 11, color: colors.textMuted },
  meta: { ...typography.caption, fontSize: 12, color: colors.textMuted },
  refs: { ...typography.caption, fontSize: 11, color: colors.textMuted },
  macros: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 4 },
  macro: { alignItems: 'center', gap: 1 },
  macroValue: { ...typography.body, fontSize: 13, fontWeight: '700', color: colors.text },
  macroLabel: { ...typography.caption, fontSize: 10, color: colors.textMuted },
});
