import { useEffect, useState } from 'react';
import { View, Text, Pressable, TextInput, Image, StyleSheet, ActivityIndicator } from 'react-native';
import { colors, spacing, radii, typography } from '../../../../theme';
import { searchRecipeImage, chooseRecipeImage, PexelsPhoto } from '../../../../api/recipeImport';

type Props = {
  recipeId: number;
  recipeName: string;
  onFinish: () => void;
};

// Calque `templates/recipe_import/index.html.twig` (panneau 5 "Photo") — recherche
// Pexels, dernière étape après l'enregistrement de la recette.
export function PhotoStep({ recipeId, recipeName, onFinish }: Props) {
  const [query, setQuery] = useState(recipeName);
  const [results, setResults] = useState<PexelsPhoto[] | null>(null);
  const [searching, setSearching] = useState(false);
  const [choosingUrl, setChoosingUrl] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  function runSearch(q: string) {
    setSearching(true);
    setError(null);
    searchRecipeImage(recipeId, q)
      .then((res) => setResults(res.results))
      .catch((err) => setError(err instanceof Error ? err.message : 'Recherche impossible — réessayez.'))
      .finally(() => setSearching(false));
  }

  useEffect(() => {
    runSearch(recipeName);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function choose(photo: PexelsPhoto) {
    setChoosingUrl(photo.downloadUrl);
    chooseRecipeImage(recipeId, photo.downloadUrl)
      .then(() => onFinish())
      .catch((err) => {
        setError(err instanceof Error ? err.message : "Erreur lors de l'attachement de la photo.");
        setChoosingUrl(null);
      });
  }

  return (
    <View style={styles.wrap}>
      <Text style={styles.kick}>Étape 6 / 6</Text>
      <Text style={styles.h2}>Ajoutez une photo</Text>
      <Text style={styles.help}>Recette enregistrée ! Recherchez une photo libre de droits (Pexels) — ou passez cette étape.</Text>

      <View style={styles.searchRow}>
        <TextInput
          style={styles.input}
          value={query}
          onChangeText={setQuery}
          placeholder="Ex. : tarte salée au thon"
          placeholderTextColor={colors.textMuted}
          onSubmitEditing={() => runSearch(query)}
        />
        <Pressable style={styles.searchBtn} onPress={() => runSearch(query)}>
          <Text style={styles.searchBtnText}>Rechercher</Text>
        </Pressable>
      </View>

      {error && <Text style={styles.error}>{error}</Text>}

      {searching ? (
        <ActivityIndicator color={colors.primary} style={{ marginTop: spacing.md }} />
      ) : results && results.length === 0 ? (
        <Text style={styles.empty}>Aucun résultat pour cette recherche.</Text>
      ) : (
        <View style={styles.grid}>
          {(results ?? []).map((photo) => (
            <Pressable key={photo.id} style={styles.item} onPress={() => choose(photo)} disabled={choosingUrl !== null}>
              <Image source={{ uri: photo.thumbnailUrl }} style={styles.itemImg} />
              {choosingUrl === photo.downloadUrl && (
                <View style={styles.itemOverlay}><ActivityIndicator color="#fff" /></View>
              )}
              <Text style={styles.credit} numberOfLines={1}>{photo.photographer} · Pexels</Text>
            </Pressable>
          ))}
        </View>
      )}

      <View style={styles.actions}>
        <Pressable style={styles.ghostBtn} onPress={onFinish}>
          <Text style={styles.ghostBtnText}>Passer cette étape</Text>
        </Pressable>
        <Pressable style={styles.primaryBtn} onPress={onFinish}>
          <Text style={styles.primaryBtnText}>Voir la recette</Text>
        </Pressable>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  wrap: { gap: spacing.sm },
  kick: { ...typography.caption, fontSize: 11.5, fontWeight: '800', color: colors.primary, textTransform: 'uppercase', letterSpacing: 0.5 },
  h2: { ...typography.title, fontSize: 20, color: colors.text },
  help: { ...typography.body, fontSize: 13.5, color: colors.textMuted, marginBottom: spacing.xs },
  searchRow: { flexDirection: 'row', gap: spacing.sm },
  input: { flex: 1, borderWidth: 1, borderColor: colors.border, borderRadius: radii.sm, paddingHorizontal: spacing.sm, paddingVertical: spacing.sm + 2, color: colors.text, backgroundColor: colors.card },
  searchBtn: { paddingVertical: spacing.sm + 2, paddingHorizontal: spacing.md, borderRadius: radii.sm, borderWidth: 1, borderColor: colors.border, alignItems: 'center', justifyContent: 'center' },
  searchBtnText: { fontSize: 13.5, fontWeight: '700', color: colors.text },
  error: { fontSize: 13, color: colors.danger },
  empty: { fontSize: 13, color: colors.textMuted, fontStyle: 'italic', textAlign: 'center', paddingVertical: spacing.lg },
  grid: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
  item: { width: '31%', gap: 3 },
  itemImg: { width: '100%', aspectRatio: 1, borderRadius: radii.sm, backgroundColor: colors.border },
  itemOverlay: { ...StyleSheet.absoluteFillObject, backgroundColor: 'rgba(20,20,26,0.45)', borderRadius: radii.sm, alignItems: 'center', justifyContent: 'center' },
  credit: { fontSize: 9.5, color: colors.textMuted },
  actions: { flexDirection: 'row', gap: spacing.sm, marginTop: spacing.sm },
  ghostBtn: { flex: 1, paddingVertical: spacing.sm + 2, borderRadius: radii.sm, borderWidth: 1, borderColor: colors.border, alignItems: 'center', justifyContent: 'center' },
  ghostBtnText: { fontSize: 14, fontWeight: '700', color: colors.textMuted },
  primaryBtn: { flex: 1, paddingVertical: spacing.sm + 2, borderRadius: radii.sm, backgroundColor: colors.primary, alignItems: 'center', justifyContent: 'center' },
  primaryBtnText: { color: '#fff', fontWeight: '700', fontSize: 14 },
});
