import { useState } from 'react';
import { View, Text, Pressable, StyleSheet, Platform, Image, Modal, ScrollView } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { MealPlanItem } from '../../../api/mealPlanning';
import { colors, spacing, radii, typography } from '../../../theme';
import { WEB_URL } from '../../../api/client';
import { SOURCE_LABEL, SOURCE_TINT } from '../utils/mealSource';

const isWeb = Platform.OS === 'web';

// Même convention que RecipeCard.tsx/AutofillModal.tsx : chemin relatif tel quel sur web
// (même origine), préfixé par WEB_URL sur natif (bundle mobile sur un hôte distinct).
function imageUri(imageUrl: string | null): string | null {
  if (!imageUrl) return null;
  return isWeb ? imageUrl : `${WEB_URL}${imageUrl}`;
}

const TYPE_TINT: Record<string, { bg: string; fg: string }> = {
  recipe: { bg: '#e9f1fe', fg: '#2f80ed' },
  ai: { bg: '#eeecfd', fg: '#5b4fe9' },
};

type Props = {
  item: MealPlanItem;
  isFirst: boolean;
  isLast: boolean;
  onMoveUp: () => void;
  onMoveDown: () => void;
  onRemove: () => void;
  // Couleur d'accent de la section (lunch/dinner/...) — utilisée uniquement pour
  // teinter le badge sur mobile-web (voir maquette "Mes Repas"), ignorée en natif.
  accentColor?: string;
  // Ouvre le sélecteur de jour (report à une autre date) — seulement pour Midi/Soir
  // (voir MealPlanningScreen.tsx::renderDayList), absent pour Petit-déjeuner/Collation qui
  // n'ont pas de notion de jour. Posé sur le titre/sous-titre uniquement (pas sur toute la
  // carte) pour rester isolé des boutons ↑/↓/✕, déjà des Pressable frères.
  onMoveToDate?: () => void;
};

const badgeLabel = (type: string) =>
  type === 'text' ? 'Tt' : type === 'food' ? 'Al' : type === 'recipe' ? 'Re' : 'IA';

export function MealItemCard({ item, isFirst, isLast, onMoveUp, onMoveDown, onRemove, accentColor, onMoveToDate }: Props) {
  const tint = TYPE_TINT[item.type] ?? { bg: `${colors.primary}1a`, fg: colors.primary };
  const photo = imageUri(item.imageUrl);
  // Aperçu en grand — un Pressable dédié posé uniquement sur la photo (jamais sur le
  // titre/sous-titre, qui reste le déclencheur du report de date via onMoveToDate) pour ne
  // pas interférer avec ce tap-là.
  const [previewOpen, setPreviewOpen] = useState(false);
  // "Ouvrir" — recette catalogue (type 'recipe') ou idée IA (type 'ai', pas de fiche
  // recette, voir MealPlanItem::$ingredients côté backend) : la seule différence est la
  // destination (fiche recette vs popin locale listant les ingrédients de l'idée).
  const navigation = useNavigation();
  const [aiDetailOpen, setAiDetailOpen] = useState(false);
  const canOpen = (item.type === 'recipe' && item.recipeId !== null) || item.type === 'ai';

  function openItem() {
    if (item.type === 'recipe' && item.recipeId !== null) {
      if (Platform.OS === 'web') {
        window.location.href = `/recettes/${item.recipeId}`;
        return;
      }
      (navigation as any).navigate('RecipeDetail', { id: item.recipeId });
      return;
    }
    if (item.type === 'ai') {
      setAiDetailOpen(true);
    }
  }

  // Mise en page mobile-web dédiée (une seule ligne : badge + titre + actions), calquée
  // sur la maquette Claude Design "Mes Repas" — le natif garde la mise en page historique
  // (badge/actions en tête, titre en dessous) pour ne pas modifier l'app mobile.
  if (isWeb) {
    const webTint = accentColor ? { bg: `${accentColor}22`, fg: accentColor } : tint;
    return (
      <View style={webStyles.card}>
        {photo ? (
          <Pressable onPress={() => setPreviewOpen(true)} hitSlop={4}>
            <Image source={{ uri: photo }} style={webStyles.photo} />
          </Pressable>
        ) : (
          <View style={[webStyles.badge, { backgroundColor: webTint.bg }]}>
            <Text style={[webStyles.badgeText, { color: webTint.fg }]}>{badgeLabel(item.type)}</Text>
          </View>
        )}
        <Pressable style={webStyles.body} onPress={onMoveToDate} disabled={!onMoveToDate}>
          <Text style={webStyles.title} numberOfLines={1}>{item.title}</Text>
          {item.subtitle ? <Text style={webStyles.subtitle} numberOfLines={1}>{item.subtitle}</Text> : null}
          {renderSourceBadge(item.source, webStyles.sourceBadge, webStyles.sourceBadgeText)}
        </Pressable>
        <View style={webStyles.actions}>
          {canOpen ? (
            <Pressable onPress={openItem} hitSlop={6} style={webStyles.actionBtn}>
              <Ionicons name="open-outline" size={16} color={colors.textMuted} />
            </Pressable>
          ) : null}
          <Pressable onPress={onMoveUp} disabled={isFirst} hitSlop={6} style={webStyles.actionBtn}>
            <Ionicons name="chevron-up" size={15} color={isFirst ? colors.border : colors.textMuted} />
          </Pressable>
          <Pressable onPress={onMoveDown} disabled={isLast} hitSlop={6} style={webStyles.actionBtn}>
            <Ionicons name="chevron-down" size={15} color={isLast ? colors.border : colors.textMuted} />
          </Pressable>
          {item.canRemove ? (
            <Pressable onPress={onRemove} hitSlop={6} style={webStyles.actionBtn}>
              <Ionicons name="close" size={16} color="#dc4444" />
            </Pressable>
          ) : null}
        </View>
        {renderPhotoPreviewModal(photo, previewOpen, () => setPreviewOpen(false))}
        {renderAiDetailModal(item, aiDetailOpen, () => setAiDetailOpen(false))}
      </View>
    );
  }

  return (
    <View style={styles.card}>
      <View style={styles.head}>
        {photo ? (
          <Pressable onPress={() => setPreviewOpen(true)} hitSlop={4}>
            <Image source={{ uri: photo }} style={styles.photo} />
          </Pressable>
        ) : (
          <View style={[styles.badge, { backgroundColor: tint.bg }]}>
            <Text style={[styles.badgeText, { color: tint.fg }]}>{badgeLabel(item.type)}</Text>
          </View>
        )}
        <View style={styles.sp} />
        {canOpen ? (
          <Pressable onPress={openItem} hitSlop={6} style={styles.moveBtn}>
            <Ionicons name="open-outline" size={15} color={colors.textMuted} />
          </Pressable>
        ) : null}
        <Pressable onPress={onMoveUp} disabled={isFirst} hitSlop={6} style={styles.moveBtn}>
          <Ionicons name="chevron-up" size={15} color={isFirst ? colors.border : colors.textMuted} />
        </Pressable>
        <Pressable onPress={onMoveDown} disabled={isLast} hitSlop={6} style={styles.moveBtn}>
          <Ionicons name="chevron-down" size={15} color={isLast ? colors.border : colors.textMuted} />
        </Pressable>
        {item.canRemove ? (
          <Pressable onPress={onRemove} hitSlop={6} style={styles.moveBtn}>
            <Ionicons name="close" size={15} color={colors.textMuted} />
          </Pressable>
        ) : null}
      </View>
      <Pressable onPress={onMoveToDate} disabled={!onMoveToDate}>
        <Text style={styles.title}>{item.title}</Text>
        {item.subtitle ? <Text style={styles.subtitle}>{item.subtitle}</Text> : null}
        {renderSourceBadge(item.source, styles.sourceBadge, styles.sourceBadgeText)}
      </Pressable>
      {renderPhotoPreviewModal(photo, previewOpen, () => setPreviewOpen(false))}
      {renderAiDetailModal(item, aiDetailOpen, () => setAiDetailOpen(false))}
    </View>
  );
}

// Même principe que la popin de revue (AutofillModal.tsx) : fond sombre plein écran,
// photo en `contain`, fermeture au tap n'importe où.
function renderPhotoPreviewModal(photo: string | null, visible: boolean, onClose: () => void) {
  if (!photo) return null;
  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
      <Pressable style={previewStyles.backdrop} onPress={onClose}>
        <Image source={{ uri: photo }} style={previewStyles.image} resizeMode="contain" />
      </Pressable>
    </Modal>
  );
}

// Idée IA : pas de fiche recette (voir MealPlanItem::$ingredients côté backend), donc pas
// de RecipeDetailScreen à ouvrir — popin locale reprenant l'aperçu déjà affiché à la
// confirmation de l'idée (AddMealModal.tsx, step "iaResult").
function renderAiDetailModal(item: MealPlanItem, visible: boolean, onClose: () => void) {
  if (item.type !== 'ai') return null;
  return (
    <Modal visible={visible} transparent animationType="slide" onRequestClose={onClose}>
      <Pressable style={aiDetailStyles.backdrop} onPress={onClose}>
        <Pressable style={aiDetailStyles.sheet} onPress={(e) => e.stopPropagation()}>
          <View style={aiDetailStyles.header}>
            <View style={{ flex: 1 }}>
              <Text style={aiDetailStyles.title}>{item.title}</Text>
              {item.subtitle ? <Text style={aiDetailStyles.subtitle}>{item.subtitle}</Text> : null}
            </View>
            <Pressable onPress={onClose} hitSlop={8} style={aiDetailStyles.closeBtn}>
              <Ionicons name="close" size={16} color={colors.textMuted} />
            </Pressable>
          </View>
          {item.ingredients.length > 0 ? (
            <ScrollView style={aiDetailStyles.list}>
              <Text style={aiDetailStyles.sectionLabel}>Ingrédients</Text>
              {item.ingredients.map((ing, index) => (
                <View key={index} style={aiDetailStyles.ingredientRow}>
                  <Text style={aiDetailStyles.ingredientName} numberOfLines={1}>{ing.name}</Text>
                  <Text style={aiDetailStyles.ingredientQty}>{ing.quantity} {ing.unit}</Text>
                </View>
              ))}
            </ScrollView>
          ) : null}
        </Pressable>
      </Pressable>
    </Modal>
  );
}

// Badge d'origine ("Suivi"/"Mes recettes"/"Recettes"/"Repas fixe") — même libellé/couleur
// que la popin de revue (AutofillModal.tsx), absent si l'item n'a pas de recette liée.
function renderSourceBadge(source: string | null, badgeStyle: object, textStyle: object) {
  if (!source || !SOURCE_LABEL[source]) return null;
  const tint = SOURCE_TINT[source] ?? SOURCE_TINT.catalog;
  return (
    <View style={[badgeStyle, { backgroundColor: tint.bg }]}>
      <Text style={[textStyle, { color: tint.fg }]}>{SOURCE_LABEL[source]}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  card: { backgroundColor: colors.card, borderWidth: 1, borderColor: colors.border, borderRadius: radii.md, padding: spacing.sm + 4, gap: 6 },
  head: { flexDirection: 'row', alignItems: 'center', gap: 6 },
  badge: { minWidth: 24, height: 22, borderRadius: 7, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 5 },
  badgeText: { fontSize: 10.5, fontWeight: '800' },
  photo: { width: 32, height: 32, borderRadius: 8, backgroundColor: colors.background },
  sp: { flex: 1 },
  moveBtn: { padding: 2 },
  title: { ...typography.body, fontSize: 14.5, fontWeight: '600', color: colors.text },
  subtitle: { ...typography.caption, fontSize: 12.5, color: colors.textMuted },
  sourceBadge: { alignSelf: 'flex-start', borderRadius: radii.pill, paddingVertical: 2, paddingHorizontal: 7, marginTop: 4 },
  sourceBadgeText: { fontSize: 10, fontWeight: '700' },
});

const webStyles = StyleSheet.create({
  card: {
    flexDirection: 'row', alignItems: 'center', gap: 14,
    backgroundColor: colors.card, borderWidth: 1, borderColor: colors.border, borderRadius: 14,
    paddingVertical: 14, paddingHorizontal: 16,
    ...(Platform.OS === 'web' ? ({ boxShadow: '0 1px 2px rgba(15,23,42,0.05)' } as any) : {}),
  },
  badge: { width: 38, height: 38, borderRadius: 10, alignItems: 'center', justifyContent: 'center', flexShrink: 0 },
  badgeText: { fontSize: 12.5, fontWeight: '700' },
  photo: { width: 38, height: 38, borderRadius: 10, flexShrink: 0, backgroundColor: colors.background },
  body: { flex: 1, gap: 2, minWidth: 0 },
  title: { fontSize: 15, fontWeight: '600', color: colors.text },
  subtitle: { fontSize: 12.5, color: colors.textMuted },
  sourceBadge: { alignSelf: 'flex-start', borderRadius: radii.pill, paddingVertical: 2, paddingHorizontal: 7, marginTop: 3 },
  sourceBadgeText: { fontSize: 10, fontWeight: '700' },
  actions: { flexDirection: 'row', alignItems: 'center', gap: 2, flexShrink: 0 },
  actionBtn: { width: 28, height: 28, borderRadius: 8, alignItems: 'center', justifyContent: 'center' },
});

const previewStyles = StyleSheet.create({
  backdrop: { flex: 1, backgroundColor: 'rgba(10, 10, 14, 0.92)', alignItems: 'center', justifyContent: 'center' },
  image: { width: '100%', height: '80%' },
});

// Même gabarit que ItemUsagesModal.tsx (liste de courses) : feuille bas d'écran, en-tête
// titre/sous-titre + croix, liste scrollable en dessous.
const aiDetailStyles = 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 },
  sectionLabel: { ...typography.caption, fontSize: 12, fontWeight: '700', color: colors.textMuted, marginBottom: 6 },
  ingredientRow: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between',
    paddingVertical: 10, paddingHorizontal: spacing.sm, borderRadius: radii.sm,
    borderWidth: 1, borderColor: colors.border, marginBottom: 6,
  },
  ingredientName: { ...typography.body, fontSize: 14, fontWeight: '600', color: colors.text, flexShrink: 1, marginRight: spacing.sm },
  ingredientQty: { ...typography.caption, fontSize: 12, fontWeight: '700', color: colors.text },
});
