import { useState } from 'react';
import { View, Text, Pressable, StyleSheet, ScrollView, ActivityIndicator, Image, Linking, Platform } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Ionicons from '@expo/vector-icons/Ionicons';
import { LinearGradient } from 'expo-linear-gradient';
import { colors, spacing, radii, typography } from '../../../theme';
import { WEB_URL } from '../../../api/client';
import { confirmAlert } from '../../../utils/alert';
import { useRecipe, useToggleFavorite, useDeleteRecipe } from '../hooks/useRecipes';
import { NutritionDonut } from '../components/NutritionDonut';

type Props = { id: number };
type TabKey = 'apercu' | 'recipe' | 'ingredients' | 'infos';

const TABS: { key: TabKey; label: string }[] = [
  { key: 'apercu', label: 'Aperçu' },
  { key: 'recipe', label: 'Recette' },
  { key: 'ingredients', label: 'Ingrédients' },
  { key: 'infos', label: 'Infos' },
];

const REFERENCE_BARS: { key: string; name: string; unit: string; color: string; sub?: boolean }[] = [
  { key: 'protein', name: 'Protéines', unit: 'g', color: '#6366f1' },
  { key: 'carbs', name: 'Glucides', unit: 'g', color: '#f59e0b' },
  { key: 'sugars', name: 'dont sucres', unit: 'g', color: '#fbbf24', sub: true },
  { key: 'fat', name: 'Lipides', unit: 'g', color: '#f43f5e' },
  { key: 'saturatedFat', name: 'dont acides gras saturés', unit: 'g', color: '#fb7185', sub: true },
  { key: 'fiber', name: 'Fibres', unit: 'g', color: '#10b981' },
  { key: 'sodium', name: 'Sodium', unit: 'mg', color: '#64748b' },
];

function formatQty(qty: number) {
  const rounded = Math.round(qty * 10) / 10;
  return Number.isInteger(rounded) ? String(rounded) : String(rounded).replace('.', ',');
}

// Calque `templates/recipe_catalog/show.html.twig` — design "1a" (maquette projet Design
// 412b0eb8-9b39-45a6-8b85-337c3bdd978b) avec l'onglet "Aperçu" du design "1c" en onglet
// par défaut. Le stepper "nombre de personnes" recalcule les quantités d'ingrédients à
// l'affichage (rien n'est envoyé/persisté), même logique que l'ex-stepper Twig
// `initServingsStepper()`. Les infos diététiques (onglet "Infos" + tuile "kcal" de
// l'aperçu) sont toujours données POUR UNE PART (recipe.servings sert de diviseur fixe),
// indépendamment de la valeur courante du stepper.
// "Modifier" ouvre `RecipeImportScreen.tsx` en mode édition (voir `editRecipeId`).
export function RecipeDetailScreen({ id }: Props) {
  const navigation = useNavigation();
  const insets = useSafeAreaInsets();
  const [tab, setTab] = useState<TabKey>('apercu');
  const [servingsOverride, setServingsOverride] = useState<number | null>(null);
  const { data: recipe, isLoading, error } = useRecipe(id);
  const toggleFavorite = useToggleFavorite(id);
  const deleteRecipe = useDeleteRecipe(id);

  function goBack() {
    if (Platform.OS === 'web') {
      window.location.href = '/recettes';
      return;
    }
    navigation.goBack();
  }

  function openEdit() {
    if (Platform.OS === 'web') {
      window.location.href = `/import/recette/${id}/modifier`;
      return;
    }
    (navigation as any).navigate('RecipeImport', { editRecipeId: id });
  }

  function handleActionPress() {
    if (!recipe) return;

    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(undefined, { onSuccess: goBack }),
      );
      return;
    }

    toggleFavorite.mutate();
  }

  if (isLoading) {
    return (
      <View style={styles.center}>
        <ActivityIndicator color={colors.primary} />
      </View>
    );
  }

  if (error || !recipe) {
    return (
      <View style={styles.center}>
        <Text style={typography.body}>Impossible de charger la recette.</Text>
      </View>
    );
  }

  const baseServings = recipe.servings ?? 1;
  const servings = servingsOverride ?? baseServings;
  const servingsRatio = servings / baseServings;
  const perPartFactor = 1 / baseServings;
  const perPartTotals = {
    kcal: recipe.nutrition.totals.kcal * perPartFactor,
    protein: recipe.nutrition.totals.protein * perPartFactor,
    carbs: recipe.nutrition.totals.carbs * perPartFactor,
    sugars: recipe.nutrition.totals.sugars * perPartFactor,
    fat: recipe.nutrition.totals.fat * perPartFactor,
    saturatedFat: recipe.nutrition.totals.saturatedFat * perPartFactor,
    fiber: recipe.nutrition.totals.fiber * perPartFactor,
    sodium: recipe.nutrition.totals.sodium * perPartFactor,
  };

  const imageUri = recipe.imageUrl ? (Platform.OS === 'web' ? recipe.imageUrl : `${WEB_URL}${recipe.imageUrl}`) : null;
  const captionParts = [
    recipe.categoryLabel,
    recipe.moodLabel,
    !recipe.isMine && recipe.ownerName ? `Par ${recipe.ownerName}` : recipe.isAbandoned ? 'Recette abandonnée' : null,
  ].filter(Boolean);

  const renderAppliances = () => {
    if (recipe.appliances.length === 0) return null;
    return (
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Appareils nécessaires</Text>
        <View style={styles.appliancesRow}>
          {recipe.appliances.map((name) => (
            <View key={name} style={styles.applianceChip}>
              <Text style={styles.applianceText}>{name}</Text>
            </View>
          ))}
        </View>
      </View>
    );
  };

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      <LinearGradient
        colors={recipe.categoryGradient}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={[styles.hero, { paddingTop: insets.top + spacing.md }]}
      >
        {imageUri && <Image source={{ uri: imageUri }} style={StyleSheet.absoluteFillObject} />}
        <View style={styles.heroOverlay} />

        <View style={styles.heroTop}>
          <Pressable style={styles.heroBtn} onPress={goBack} accessibilityLabel="Retour">
            <Ionicons name="arrow-back" size={17} color="#fff" />
          </Pressable>
          <View style={styles.heroTopActions}>
            {recipe.isMine && (
              <Pressable style={styles.heroBtn} onPress={openEdit} accessibilityLabel="Modifier">
                <Ionicons name="create-outline" size={17} color="#fff" />
              </Pressable>
            )}
            <Pressable
              style={styles.heroBtn}
              onPress={handleActionPress}
              disabled={toggleFavorite.isPending || deleteRecipe.isPending}
              accessibilityLabel={recipe.isMine ? 'Supprimer' : recipe.isFavorite ? 'Retirer' : 'Ajouter'}
            >
              <Ionicons
                name={recipe.isMine ? 'trash-outline' : recipe.isFavorite ? 'heart' : 'heart-outline'}
                size={17}
                color="#fff"
              />
            </Pressable>
          </View>
        </View>

        <View style={styles.heroCaption}>
          <Text style={styles.heroOverline}>{captionParts.join(' · ')}</Text>
          <Text style={styles.heroName}>{recipe.name}</Text>
          <View style={styles.heroChips}>
            {recipe.prepTimeMinutes !== null && (
              <View style={styles.heroChip}>
                <Ionicons name="time-outline" size={13} color="#fff" />
                <Text style={styles.heroChipText}>{recipe.prepTimeMinutes} min</Text>
              </View>
            )}
            {recipe.servings !== null && (
              <View style={[styles.heroChip, styles.heroChipStepper]}>
                <Pressable
                  style={styles.servStepBtn}
                  disabled={servings <= 1}
                  onPress={() => setServingsOverride(Math.max(1, servings - 1))}
                >
                  <Ionicons name="remove" size={13} color="#fff" />
                </Pressable>
                <Ionicons name="people-outline" size={13} color="#fff" />
                <Text style={styles.heroChipText}>
                  {servings} part{servings > 1 ? 's' : ''}
                </Text>
                <Pressable style={styles.servStepBtn} onPress={() => setServingsOverride(servings + 1)}>
                  <Ionicons name="add" size={13} color="#fff" />
                </Pressable>
              </View>
            )}
            <View style={styles.heroChip}>
              <Ionicons name="nutrition-outline" size={13} color="#fff" />
              <Text style={styles.heroChipText}>
                {recipe.ingredients.length} ingrédient{recipe.ingredients.length > 1 ? 's' : ''}
              </Text>
            </View>
            {recipe.appliances.length > 0 && (
              <View style={styles.heroChip}>
                <Text style={styles.heroChipText}>
                  {recipe.appliances.length} appareil{recipe.appliances.length > 1 ? 's' : ''}
                </Text>
              </View>
            )}
          </View>
        </View>
      </LinearGradient>

      {recipe.dietTags.length > 0 && (
        <View style={styles.tagsRow}>
          {recipe.dietTags.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.tabs}>
        {TABS.map((t) => (
          <Pressable key={t.key} style={[styles.tab, tab === t.key && styles.tabActive]} onPress={() => setTab(t.key)}>
            <Text style={[styles.tabText, tab === t.key && styles.tabTextActive]}>{t.label}</Text>
          </Pressable>
        ))}
      </View>

      {tab === 'apercu' && (
        <View style={styles.tabPanel}>
          <View style={styles.bento}>
            <View style={styles.bentoTile}>
              <Text style={styles.bentoValue}>{recipe.prepTimeMinutes !== null ? `${recipe.prepTimeMinutes} min` : '—'}</Text>
              <Text style={styles.bentoLabel}>Temps total</Text>
            </View>
            <View style={styles.bentoTile}>
              <Text style={styles.bentoValue}>
                {recipe.servings !== null ? `${servings} part${servings > 1 ? 's' : ''}` : '—'}
              </Text>
              <Text style={styles.bentoLabel}>Portions</Text>
            </View>
            <View style={styles.bentoTile}>
              <Text style={styles.bentoValue}>{Math.round(perPartTotals.kcal)} kcal</Text>
              <Text style={styles.bentoLabel}>Par part</Text>
            </View>
            <View style={[styles.bentoTile, styles.bentoTileAccent]}>
              <Text style={[styles.bentoValue, styles.bentoValueAccent]}>{recipe.ingredients.length}</Text>
              <Text style={styles.bentoLabel}>Ingrédient{recipe.ingredients.length > 1 ? 's' : ''}</Text>
            </View>
          </View>

          {renderAppliances()}
        </View>
      )}

      {tab === 'recipe' && (
        <View style={styles.tabPanel}>
          {recipe.steps.length > 0 && (
            <View style={styles.section}>
              <Text style={styles.sectionTitle}>Préparation</Text>
              {recipe.steps.map((step) => (
                <View key={step.position} style={styles.step}>
                  <View style={styles.stepNumber}>
                    <Text style={styles.stepNumberText}>{step.position}</Text>
                  </View>
                  <Text style={styles.stepText}>{step.description}</Text>
                </View>
              ))}
            </View>
          )}
        </View>
      )}

      {tab === 'ingredients' && (
        <View style={styles.tabPanel}>
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Ingrédients</Text>
            {recipe.ingredients.map((ing, idx) => (
              <View key={idx} style={styles.ingRow}>
                <Text style={styles.ingRowName}>{ing.name}</Text>
                <Text style={styles.ingRowQty}>
                  {formatQty(ing.quantity * servingsRatio)} {ing.unit}
                </Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {tab === 'infos' && (
        <View style={styles.tabPanel}>
          {renderAppliances()}

          {(recipe.sourceUrl || recipe.videoUrl) && (
            <View style={styles.section}>
              <Text style={styles.sectionTitle}>Liens</Text>
              {recipe.sourceUrl && (
                <Pressable onPress={() => Linking.openURL(recipe.sourceUrl!)}>
                  <Text style={styles.link}>Voir la source originale ↗</Text>
                </Pressable>
              )}
              {recipe.videoUrl && (
                <Pressable onPress={() => Linking.openURL(recipe.videoUrl!)}>
                  <Text style={styles.link}>Voir la vidéo ↗</Text>
                </Pressable>
              )}
            </View>
          )}

          <View style={styles.section}>
            <NutritionDonut totals={perPartTotals} segments={recipe.nutrition.donutSegments} />
            <Text style={styles.dietNote}>
              Valeurs calculées pour une part (recette prévue pour {baseServings} part{baseServings > 1 ? 's' : ''}).
            </Text>
          </View>

          <View style={styles.section}>
            <Text style={styles.sectionSub}>Apports nutritionnels (% des apports de référence, pour une part)</Text>
            {REFERENCE_BARS.map((bar) => {
              const ref = recipe.nutrition.referenceIntakes[bar.key];
              const total = (perPartTotals as any)[bar.key] as number;
              if (!ref) return null;
              const percentage = ref.reference > 0 ? total / ref.reference : 0;
              return (
                <View key={bar.key} style={[styles.barRow, bar.sub && styles.barRowSub]}>
                  <View style={styles.barTop}>
                    <Text style={styles.barName}>
                      {bar.name} <Text style={styles.barRef}>AR {Math.round(ref.reference)} {bar.unit}</Text>
                    </Text>
                    <Text style={styles.barValue}>
                      {total.toFixed(1)} {bar.unit} <Text style={styles.barPct}>{Math.round(percentage * 100)}%</Text>
                    </Text>
                  </View>
                  <View style={styles.barTrack}>
                    <View style={[styles.barFill, { width: `${Math.max(2, percentage * 100)}%`, backgroundColor: bar.color }]} />
                  </View>
                </View>
              );
            })}
          </View>

          {recipe.nutrition.ingredients.length > 0 && (
            <View style={styles.section}>
              <Text style={styles.sectionSub}>Calories par ingrédient</Text>
              {recipe.nutrition.ingredients.map((ing, idx) => (
                <View key={idx} style={styles.breakdownRow}>
                  <View style={styles.breakdownMain}>
                    <Text style={styles.breakdownName} numberOfLines={1}>
                      {ing.name}
                    </Text>
                    <View style={styles.breakdownTrack}>
                      <View style={[styles.breakdownFill, { width: `${Math.max(2, ing.share * 100)}%` }]} />
                    </View>
                  </View>
                  <Text style={styles.breakdownKcal}>{Math.round(ing.calories * perPartFactor)} kcal</Text>
                </View>
              ))}
            </View>
          )}
        </View>
      )}
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  content: { paddingBottom: spacing.xl, gap: spacing.md },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  hero: {
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.lg,
    gap: spacing.md,
    overflow: 'hidden',
  },
  heroOverlay: { ...StyleSheet.absoluteFillObject, backgroundColor: 'rgba(0,0,0,0.18)' },
  heroTop: { flexDirection: 'row', justifyContent: 'space-between' },
  heroTopActions: { flexDirection: 'row', gap: 8 },
  heroBtn: {
    width: 34,
    height: 34,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(255,255,255,0.22)',
    borderRadius: radii.pill,
  },
  heroCaption: { gap: 4 },
  heroOverline: { fontSize: 12, fontWeight: '700', color: 'rgba(255,255,255,0.85)' },
  heroName: { fontSize: 24, fontWeight: '800', color: '#fff' },
  heroChips: { flexDirection: 'row', gap: 8, flexWrap: 'wrap', marginTop: 4 },
  heroChip: { flexDirection: 'row', alignItems: 'center', gap: 5 },
  heroChipStepper: { backgroundColor: 'rgba(255,255,255,0.18)', paddingHorizontal: 6, paddingVertical: 3, borderRadius: radii.pill },
  heroChipText: { fontSize: 12.5, fontWeight: '600', color: '#fff' },
  servStepBtn: {
    width: 18,
    height: 18,
    borderRadius: radii.pill,
    backgroundColor: 'rgba(255,255,255,0.28)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  tagsRow: { flexDirection: 'row', gap: 8, flexWrap: 'wrap', paddingHorizontal: Platform.OS === 'web' ? 2 : spacing.lg },
  tag: { paddingHorizontal: 10, paddingVertical: 5, borderRadius: radii.pill },
  tagText: { fontSize: 12, fontWeight: '700' },
  tabs: {
    flexDirection: 'row',
    gap: 4,
    marginHorizontal: Platform.OS === 'web' ? 2 : spacing.lg,
    padding: 4,
    backgroundColor: colors.surface,
    borderRadius: radii.md,
  },
  tab: { flex: 1, paddingVertical: 10, borderRadius: radii.sm, alignItems: 'center' },
  tabActive: {
    backgroundColor: colors.card,
    shadowColor: '#000',
    shadowOpacity: 0.08,
    shadowRadius: 4,
    shadowOffset: { width: 0, height: 1 },
    elevation: 1,
  },
  tabText: { fontSize: 12.5, fontWeight: '700', color: colors.textMuted },
  tabTextActive: { color: colors.text },
  tabPanel: { paddingHorizontal: Platform.OS === 'web' ? 2 : spacing.lg, gap: spacing.lg },
  bento: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
  bentoTile: { width: '47%', backgroundColor: colors.surface, borderRadius: radii.md, padding: spacing.md },
  bentoTileAccent: { backgroundColor: '#eef0fe' },
  bentoValue: { fontSize: 18, fontWeight: '800', color: colors.text },
  bentoValueAccent: { color: colors.primary },
  bentoLabel: { fontSize: 11.5, fontWeight: '600', color: colors.textMuted, marginTop: 3 },
  ingRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 11,
    borderTopWidth: 1,
    borderTopColor: colors.border,
  },
  ingRowName: { flex: 1, fontSize: 14, fontWeight: '600', color: colors.text },
  ingRowQty: { fontSize: 13, fontWeight: '700', color: colors.textMuted },
  section: { gap: spacing.sm },
  sectionTitle: { fontSize: 13.5, fontWeight: '800', color: colors.text },
  sectionSub: { fontSize: 12, fontWeight: '700', color: colors.textMuted, textTransform: 'uppercase', letterSpacing: 0.3 },
  step: { flexDirection: 'row', gap: spacing.sm, alignItems: 'flex-start' },
  stepNumber: { width: 24, height: 24, borderRadius: radii.pill, backgroundColor: '#eef0fe', alignItems: 'center', justifyContent: 'center' },
  stepNumberText: { fontSize: 12, fontWeight: '800', color: colors.primary },
  stepText: { flex: 1, fontSize: 14, color: colors.text, lineHeight: 20 },
  appliancesRow: { flexDirection: 'row', gap: 8, flexWrap: 'wrap' },
  applianceChip: { backgroundColor: colors.surface, paddingHorizontal: 10, paddingVertical: 6, borderRadius: radii.pill },
  applianceText: { fontSize: 12.5, fontWeight: '600', color: colors.text },
  link: { fontSize: 13.5, fontWeight: '700', color: colors.primary, marginTop: 2 },
  dietNote: { fontSize: 12, color: colors.textMuted },
  barRow: { gap: 5 },
  barRowSub: { paddingLeft: spacing.md, opacity: 0.85 },
  barTop: { flexDirection: 'row', justifyContent: 'space-between' },
  barName: { fontSize: 12.5, fontWeight: '700', color: colors.text },
  barRef: { fontSize: 10.5, fontWeight: '600', color: colors.textMuted },
  barValue: { fontSize: 12.5, fontWeight: '700', color: colors.text },
  barPct: { fontSize: 10.5, fontWeight: '600', color: colors.textMuted },
  barTrack: { height: 6, borderRadius: radii.pill, backgroundColor: colors.surface, overflow: 'hidden' },
  barFill: { height: '100%', borderRadius: radii.pill },
  breakdownRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
  breakdownMain: { flex: 1, gap: 4 },
  breakdownName: { fontSize: 12.5, fontWeight: '600', color: colors.text },
  breakdownTrack: { height: 4, borderRadius: radii.pill, backgroundColor: colors.surface, overflow: 'hidden' },
  breakdownFill: { height: '100%', borderRadius: radii.pill, backgroundColor: colors.primary },
  breakdownKcal: { fontSize: 12, fontWeight: '700', color: colors.textMuted },
});
