import { Modal, View, Text, Pressable, StyleSheet, ScrollView } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { ShoppingItem } from '../../../api/shoppingList';
import { colors, spacing, radii, typography } from '../../../theme';
import { dayInfo } from '../../meal-planning/utils/weekDates';

type Props = {
  visible: boolean;
  item: ShoppingItem | null;
  onClose: () => void;
};

// Petit-déjeuner/Collation n'ont pas de jour assigné (catégories non datées, voir
// MealPlanItem côté backend) — dans ce cas on n'affiche que la catégorie de repas.
function usageDateLabel(plannedDate: string | null): string | null {
  if (plannedDate === null) return null;
  const { weekday, short } = dayInfo(plannedDate);
  return `${weekday} ${short}`;
}

export function ItemUsagesModal({ visible, item, onClose }: Props) {
  if (!item) return null;

  return (
    <Modal visible={visible} transparent animationType="slide" onRequestClose={onClose}>
      <Pressable style={styles.backdrop} onPress={onClose}>
        <Pressable style={styles.sheet} onPress={(e) => e.stopPropagation()}>
          <View style={styles.header}>
            <View style={{ flex: 1 }}>
              <Text style={styles.title}>Utilisé dans</Text>
              <Text style={styles.subtitle} numberOfLines={1}>{item.name}</Text>
            </View>
            <Pressable onPress={onClose} hitSlop={8} style={styles.closeBtn}>
              <Ionicons name="close" size={16} color={colors.textMuted} />
            </Pressable>
          </View>

          <ScrollView style={styles.list}>
            {item.usages.map((usage, index) => {
              const dateLabel = usageDateLabel(usage.plannedDate);
              return (
                <View key={index} style={styles.usageRow}>
                  <View style={{ flex: 1 }}>
                    <Text style={styles.recipeName} numberOfLines={1}>{usage.recipeName}</Text>
                    <Text style={styles.categoryLabel}>
                      {dateLabel ? `${dateLabel} · ${usage.categoryLabel}` : usage.categoryLabel}
                    </Text>
                  </View>
                  <Text style={styles.qty}>{usage.quantity}</Text>
                </View>
              );
            })}
          </ScrollView>
        </Pressable>
      </Pressable>
    </Modal>
  );
}

const styles = StyleSheet.create({
  backdrop: { flex: 1, backgroundColor: 'rgba(20, 20, 26, 0.4)', justifyContent: 'flex-end' },
  sheet: { backgroundColor: colors.card, borderTopLeftRadius: radii.xl, borderTopRightRadius: radii.xl, padding: spacing.lg, maxHeight: '80%' },
  header: { flexDirection: 'row', alignItems: 'flex-start', marginBottom: spacing.md },
  title: { ...typography.title, fontSize: 18, color: colors.text },
  subtitle: { ...typography.caption, color: colors.textMuted, marginTop: 2 },
  closeBtn: { width: 30, height: 30, borderRadius: radii.pill, backgroundColor: colors.background, alignItems: 'center', justifyContent: 'center' },
  list: { maxHeight: 420 },
  usageRow: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between',
    paddingVertical: 10, paddingHorizontal: spacing.sm, borderRadius: radii.sm,
    borderWidth: 1, borderColor: colors.border, marginBottom: 6,
  },
  recipeName: { ...typography.body, fontSize: 14, fontWeight: '600', color: colors.text },
  categoryLabel: { ...typography.caption, fontSize: 11, color: colors.textMuted, marginTop: 2 },
  qty: { ...typography.caption, fontSize: 12, fontWeight: '700', color: colors.text },
});
