import { useState } from 'react';
import { View, Text, TextInput, Pressable, StyleSheet } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { AnalyzedIngredient } from '../../../api/tracking';
import { colors, spacing, typography, radii } from '../../../theme';

function formatQty(qty: number) {
  return Number.isInteger(qty) ? String(qty) : qty.toFixed(1);
}

type Props = {
  ingredient: AnalyzedIngredient;
  onChangeQuantity: (quantity: number) => void;
  onRemove: () => void;
};

// Ligne d'ingrédient éditable (quantité), partagée entre l'écran de résultat IA
// (`PhotoCaptureModal`) et la relecture d'une entrée de l'historique
// (`EntryDetailModal`). Texte de saisie local (pas directement `String(quantity)`) pour
// pouvoir taper une valeur intermédiaire ("20," en cours de frappe d'un décimal) sans
// que chaque frappe ne re-formate le champ — la quantité n'est commise (et
// kcal/protein/carbs/fat recalculés proportionnellement) qu'à la perte du focus.
export function IngredientRow({ ingredient, onChangeQuantity, onRemove }: Props) {
  const [draft, setDraft] = useState(formatQty(ingredient.quantity));

  function commit() {
    const parsed = parseFloat(draft.replace(',', '.'));
    if (Number.isFinite(parsed) && parsed > 0) {
      onChangeQuantity(parsed);
    } else {
      setDraft(formatQty(ingredient.quantity));
    }
  }

  return (
    <View style={styles.row}>
      <View style={{ flex: 1 }}>
        <Text style={styles.name}>{ingredient.name}</Text>
        {ingredient.ciqualName && <Text style={styles.caption}>Ciqual : {ingredient.ciqualName}</Text>}
      </View>
      <View style={styles.meta}>
        <View style={styles.qtyRow}>
          <TextInput
            style={styles.qtyInput}
            value={draft}
            onChangeText={setDraft}
            onEndEditing={commit}
            onBlur={commit}
            keyboardType="numeric"
          />
          <Text style={styles.caption}>{ingredient.unit}</Text>
        </View>
        <Text style={styles.kcal}>{Math.round(ingredient.kcal)} kcal</Text>
      </View>
      <Pressable onPress={onRemove} hitSlop={8}>
        <Ionicons name="close" size={16} color={colors.textMuted} />
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  row: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, paddingVertical: 4 },
  name: { ...typography.body, fontSize: 14, color: colors.text },
  caption: { ...typography.caption, color: colors.textMuted },
  meta: { alignItems: 'flex-end', gap: 1 },
  qtyRow: { flexDirection: 'row', alignItems: 'center', gap: 4 },
  qtyInput: {
    width: 52,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    paddingHorizontal: 6,
    paddingVertical: 2,
    ...typography.caption,
    color: colors.text,
    textAlign: 'right',
  },
  kcal: { ...typography.caption, color: colors.success, fontWeight: '700' },
});
