import { View, Text, Image, Pressable, StyleSheet, Platform } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import Ionicons from '@expo/vector-icons/Ionicons';
import { RecipeSummary } from '../../../api/recipes';
import { colors, spacing, radii } from '../../../theme';
import { WEB_URL } from '../../../api/client';
import { confirmAlert } from '../../../utils/alert';
import { useDeleteRecipe, useToggleFavorite } from '../hooks/useRecipes';

type Props = {
  recipe: RecipeSummary;
  onPress: () => void;
};

// Calque `.rc-card`/`.rc-thumb`/`.rc-fav-btn` (assets/styles/recipe-catalog.css,
// templates/recipe_catalog/index.html.twig). Chaque carte porte ses propres mutations
// favori/suppression (un hook par recette, valable puisque chaque carte est sa propre
// instance de composant — pas d'appel de hook dans une boucle du parent).
export function RecipeCard({ recipe, onPress }: Props) {
  const toggleFavorite = useToggleFavorite(recipe.id);
  const deleteRecipe = useDeleteRecipe(recipe.id);
  const actionPending = toggleFavorite.isPending || deleteRecipe.isPending;

  const imageUri = recipe.imageUrl ? (Platform.OS === 'web' ? recipe.imageUrl : `${WEB_URL}${recipe.imageUrl}`) : null;

  function handleActionPress() {
    if (recipe.isMine) {
      const message =
        recipe.favoritesCount > 0
          ? `"${recipe.name}" est dans les favoris d'un autre utilisateur : elle sera retirée de vos recettes mais restera visible pour eux. Continuer ?`
          : `Supprimer définitivement "${recipe.name}" ?`;

      confirmAlert('Supprimer la recette', message, 'Supprimer', () => deleteRecipe.mutate());
      return;
    }

    toggleFavorite.mutate();
  }

  return (
    <View style={styles.wrap}>
      <Pressable style={styles.card} onPress={onPress}>
        <LinearGradient colors={recipe.categoryGradient} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={styles.thumb}>
          {imageUri ? (
            Platform.OS === 'web' ? (
              // <img> natif => lazy-loading navigateur : la vignette n'est chargée qu'à
              // l'approche du viewport. RN Web <Image> précharge au contraire TOUTES les
              // vignettes en JS dès le montage => rafale de requêtes au chargement du
              // catalogue, 403 mod_security en prod (cf. .wolf/buglog.json bug-007).
              <img
                src={imageUri}
                alt={recipe.name}
                loading="lazy"
                decoding="async"
                style={{ width: '100%', height: '100%', objectFit: 'cover' }}
              />
            ) : (
              <Image source={{ uri: imageUri }} style={styles.thumbImage} />
            )
          ) : (
            <Ionicons name="restaurant-outline" size={40} color="rgba(255,255,255,0.92)" />
          )}
          <View style={styles.badge}>
            <Text style={styles.badgeText}>{recipe.categoryLabel}</Text>
          </View>
        </LinearGradient>

        <View style={styles.body}>
          <View style={styles.metaRow}>
            {recipe.prepTimeMinutes !== null && (
              <View style={styles.meta}>
                <Ionicons name="time-outline" size={13} color={colors.textMuted} />
                <Text style={styles.metaText}>{recipe.prepTimeMinutes} min</Text>
              </View>
            )}
            {recipe.servings !== null && (
              <View style={styles.meta}>
                <Ionicons name="people-outline" size={13} color={colors.textMuted} />
                <Text style={styles.metaText}>
                  {recipe.servings} part{recipe.servings > 1 ? 's' : ''}
                </Text>
              </View>
            )}
            {recipe.moodLabel && (
              <View style={styles.meta}>
                <Text style={styles.metaText}>{recipe.moodLabel}</Text>
              </View>
            )}
          </View>

          <Text style={styles.name} numberOfLines={2}>
            {recipe.name}
          </Text>

          {!recipe.isMine && recipe.ownerName && <Text style={styles.owner}>Par {recipe.ownerName}</Text>}
          {recipe.isMine && recipe.isAbandoned && <Text style={styles.owner}>Recette abandonnée</Text>}

          {recipe.dietTags.length > 0 && (
            <View style={styles.tags}>
              {recipe.dietTags.slice(0, 3).map((tag) => (
                <View key={tag.value} style={[styles.tag, { backgroundColor: tag.color + '18' }]}>
                  <Text style={[styles.tagText, { color: tag.color }]}>{tag.label}</Text>
                </View>
              ))}
            </View>
          )}

          <View style={styles.foot}>
            <Text style={styles.kcal}>
              {recipe.totalCalories} kcal <Text style={styles.kcalUnit}>/ recette</Text>
            </Text>
          </View>
        </View>
      </Pressable>

      <Pressable style={styles.actionBtn} onPress={handleActionPress} disabled={actionPending}>
        <Ionicons
          name={recipe.isMine ? 'trash-outline' : recipe.isFavorite ? 'heart' : 'heart-outline'}
          size={16}
          color={recipe.isFavorite ? '#e11d48' : colors.text}
        />
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  wrap: { position: 'relative', flex: 1 },
  card: { backgroundColor: colors.card, borderRadius: radii.lg, borderWidth: 1, borderColor: colors.border, overflow: 'hidden' },
  thumb: { height: 140, alignItems: 'center', justifyContent: 'center' },
  thumbImage: { width: '100%', height: '100%' },
  badge: {
    position: 'absolute',
    left: 10,
    top: 10,
    backgroundColor: 'rgba(255,255,255,0.9)',
    paddingHorizontal: 8,
    paddingVertical: 3,
    borderRadius: radii.pill,
  },
  badgeText: { fontSize: 10.5, fontWeight: '700', color: colors.text },
  body: { padding: spacing.sm + 4, gap: 7 },
  metaRow: { flexDirection: 'row', alignItems: 'center', gap: 10, flexWrap: 'wrap' },
  meta: { flexDirection: 'row', alignItems: 'center', gap: 4 },
  metaText: { fontSize: 12, fontWeight: '600', color: colors.textMuted },
  name: { fontSize: 15.5, fontWeight: '800', color: colors.text, letterSpacing: -0.2 },
  owner: { fontSize: 12, fontWeight: '600', color: colors.textMuted, marginTop: -4 },
  tags: { flexDirection: 'row', gap: 5, flexWrap: 'wrap' },
  tag: { paddingHorizontal: 8, paddingVertical: 3, borderRadius: radii.pill },
  tagText: { fontSize: 10, fontWeight: '700' },
  foot: { paddingTop: 6, borderTopWidth: 1, borderTopColor: colors.border },
  kcal: { fontSize: 13, fontWeight: '800', color: colors.primary },
  kcalUnit: { color: colors.textMuted, fontWeight: '600', fontSize: 11.5 },
  actionBtn: {
    position: 'absolute',
    top: 10,
    right: 10,
    width: 30,
    height: 30,
    borderRadius: radii.pill,
    backgroundColor: 'rgba(255,255,255,0.92)',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
