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

type PrepareProps = {
  mode: 'prepare';
  item: ShoppingItem;
  onToggleOwned: () => void;
  onIncrease: () => void;
  onDecrease: () => void;
  onSetQuantity: (value: number) => void;
  onRemove: () => void;
  onShowUsages?: () => void;
};

type ShopProps = {
  mode: 'shop';
  item: ShoppingItem;
  onToggleChecked: () => void;
  onShowUsages?: () => void;
};

type Props = PrepareProps | ShopProps;

export function ShoppingItemRow(props: Props) {
  const { item } = props;
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState('');

  if (props.mode === 'shop') {
    return (
      <View style={[styles.row, item.checked && styles.rowChecked]}>
        <Pressable style={styles.shopMain} onPress={props.onToggleChecked}>
          <View style={[styles.checkCircle, item.checked && styles.checkCircleOn]}>
            {item.checked ? <Ionicons name="checkmark" size={14} color="#fff" /> : null}
          </View>
          <View style={styles.main}>
            <Text style={[styles.name, item.checked && styles.nameChecked]}>{item.name}</Text>
          </View>
        </Pressable>
        {item.usages.length > 0 ? (
          <Pressable onPress={props.onShowUsages} hitSlop={6} style={styles.infoBtn}>
            <Ionicons name="information-circle-outline" size={17} color={colors.textMuted} />
          </Pressable>
        ) : null}
        {item.trackQuantity ? <Text style={styles.qty}>{item.quantity}</Text> : null}
      </View>
    );
  }

  const { onToggleOwned, onIncrease, onDecrease, onSetQuantity, onRemove, onShowUsages } = props;

  function submitEdit() {
    const value = Number(draft.replace(',', '.'));
    if (!Number.isNaN(value)) onSetQuantity(value);
    setEditing(false);
  }

  return (
    <View style={[styles.row, item.alreadyOwned && styles.rowChecked]}>
      <Pressable style={[styles.checkCircle, item.alreadyOwned && styles.checkCircleOn]} onPress={onToggleOwned} hitSlop={6}>
        {item.alreadyOwned ? <Ionicons name="checkmark" size={14} color="#fff" /> : null}
      </Pressable>

      <View style={styles.main}>
        <Text style={[styles.name, item.alreadyOwned && styles.nameChecked]} numberOfLines={1}>{item.name}</Text>
        {item.adjustment ? (
          <Text style={[styles.adjustment, { color: item.adjustment.positive ? colors.success : colors.danger }]}>
            {item.adjustment.label}
          </Text>
        ) : null}
      </View>

      {item.usages.length > 0 ? (
        <Pressable onPress={onShowUsages} hitSlop={6} style={styles.infoBtn}>
          <Ionicons name="information-circle-outline" size={17} color={colors.textMuted} />
        </Pressable>
      ) : null}

      {item.trackQuantity ? (
        <View style={styles.qtyBox}>
          <Pressable style={styles.qtyBtn} onPress={onDecrease} hitSlop={6}>
            <Ionicons name="remove" size={13} color={colors.text} />
          </Pressable>
          {editing ? (
            <TextInput
              style={styles.qtyInput}
              value={draft}
              onChangeText={setDraft}
              keyboardType="numeric"
              autoFocus
              onBlur={submitEdit}
              onSubmitEditing={submitEdit}
            />
          ) : (
            <Pressable onPress={() => { setDraft(''); setEditing(true); }}>
              <Text style={styles.qty}>{item.quantity}</Text>
            </Pressable>
          )}
          <Pressable style={styles.qtyBtn} onPress={onIncrease} hitSlop={6}>
            <Ionicons name="add" size={13} color={colors.text} />
          </Pressable>
        </View>
      ) : null}

      {/* Non custom = revient au prochain regenerate() tant que l'idée de repas est planifiée — cocher "déjà possédé" plus haut est le bon geste pour dire "pas besoin". */}
      {item.custom ? (
        <Pressable onPress={onRemove} hitSlop={6} style={styles.remove}>
          <Ionicons name="trash-outline" size={16} color={colors.textMuted} />
        </Pressable>
      ) : null}
    </View>
  );
}

const styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
    paddingVertical: spacing.xs,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  rowChecked: { opacity: 0.5 },
  checkCircle: {
    width: 22,
    height: 22,
    borderRadius: 11,
    borderWidth: 1.5,
    borderColor: colors.border,
    alignItems: 'center',
    justifyContent: 'center',
  },
  checkCircleOn: { backgroundColor: colors.primary, borderColor: colors.primary },
  shopMain: { flex: 1, flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
  infoBtn: { padding: 2 },
  main: { flex: 1, gap: 2 },
  name: { ...typography.body, fontSize: 14, color: colors.text },
  nameChecked: { textDecorationLine: 'line-through' },
  adjustment: { ...typography.caption, fontSize: 11, fontWeight: '600' },
  qtyBox: { flexDirection: 'row', alignItems: 'center', gap: 6 },
  qtyBtn: {
    width: 24,
    height: 24,
    borderRadius: radii.sm,
    borderWidth: 1,
    borderColor: colors.border,
    alignItems: 'center',
    justifyContent: 'center',
  },
  qty: { ...typography.caption, fontSize: 12, fontWeight: '700', color: colors.text, minWidth: 56, textAlign: 'center' },
  qtyInput: {
    ...typography.caption,
    fontSize: 12,
    fontWeight: '700',
    color: colors.text,
    minWidth: 56,
    textAlign: 'center',
    borderWidth: 1,
    borderColor: colors.primary,
    borderRadius: radii.sm,
    paddingVertical: 2,
  },
  remove: { padding: 2 },
});
