import { useEffect, useRef, useState } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, Animated } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { gradients, radii, spacing, typography } from '../../../theme';

// Mots utilisés pour l'effet "extraction d'ingrédients" du loader — mêmes mots que
// `LOADER_WORDS` dans `recipe-import.js` (web) : purement décoratif (pas liés au plat
// réellement analysé), juste pour donner une impression tangible de travail en cours,
// plutôt qu'un simple spinner qui grise l'écran.
const LOADER_WORDS = ['Saumon fumé', 'Pain', 'Câpres', 'Citron', 'Persil', 'Beurre', 'Échalote', 'Crème fraîche'];
const MAX_CHIPS = 4;
const CHIP_INTERVAL_MS = 900;

function shuffle<T>(arr: T[]): T[] {
  const copy = [...arr];
  for (let i = copy.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}

function Chip({ text }: { text: string }) {
  const anim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.sequence([
      Animated.timing(anim, { toValue: 1, duration: 250, useNativeDriver: true }),
      Animated.loop(
        Animated.sequence([
          Animated.timing(anim, { toValue: 0.55, duration: 800, useNativeDriver: true }),
          Animated.timing(anim, { toValue: 1, duration: 800, useNativeDriver: true }),
        ])
      ),
    ]).start();
  }, [anim]);

  return (
    <Animated.View
      style={[
        styles.chip,
        { opacity: anim, transform: [{ translateY: anim.interpolate({ inputRange: [0, 1], outputRange: [6, 0] }) }] },
      ]}
    >
      <Text style={styles.chipText}>{text}</Text>
    </Animated.View>
  );
}

// Loader plein écran pour les temps d'attente IA (analyse ou correction d'une photo) —
// remplace un simple spinner par des pastilles animées façon "extraction
// d'ingrédients", partagé par `PhotoCaptureModal`/`EntryDetailModal`.
export function AnalyzingOverlay({ message }: { message: string }) {
  const [chips, setChips] = useState<{ id: number; text: string }[]>([]);
  const poolRef = useRef(shuffle(LOADER_WORDS));
  const poolIndexRef = useRef(0);
  const nextIdRef = useRef(0);

  useEffect(() => {
    function addChip() {
      if (poolIndexRef.current >= poolRef.current.length) {
        poolRef.current = shuffle(LOADER_WORDS);
        poolIndexRef.current = 0;
      }
      const text = poolRef.current[poolIndexRef.current++];
      const id = nextIdRef.current++;
      setChips((list) => {
        const base = list.length >= MAX_CHIPS ? [] : list;
        return [...base, { id, text }];
      });
    }

    addChip();
    const timer = setInterval(addChip, CHIP_INTERVAL_MS);
    return () => clearInterval(timer);
  }, []);

  return (
    <View style={styles.root}>
      <LinearGradient colors={gradients.hero} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={styles.card}>
        <ActivityIndicator color="#fff" size="large" />
        <Text style={styles.text}>{message}</Text>
        <View style={styles.chipsRow}>
          {chips.map((chip) => (
            <Chip key={chip.id} text={chip.text} />
          ))}
        </View>
      </LinearGradient>
    </View>
  );
}

const styles = StyleSheet.create({
  root: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: spacing.xl },
  card: {
    width: '100%',
    maxWidth: 340,
    borderRadius: radii.xl,
    paddingVertical: spacing.xl,
    paddingHorizontal: spacing.lg,
    alignItems: 'center',
    gap: spacing.md,
  },
  text: { ...typography.body, color: '#fff', fontWeight: '700', textAlign: 'center' },
  chipsRow: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', gap: spacing.xs, minHeight: 26 },
  chip: {
    paddingHorizontal: spacing.md,
    paddingVertical: 5,
    borderRadius: radii.pill,
    backgroundColor: 'rgba(255,255,255,0.18)',
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.32)',
  },
  chipText: { color: '#fff', fontSize: 12.5, fontWeight: '700' },
});
