import { useState } from 'react';
import { View, Text, Image, Pressable, TextInput, StyleSheet, ActivityIndicator } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import Ionicons from '@expo/vector-icons/Ionicons';
import { colors, spacing, radii, typography } from '../../../../theme';
import { analyzeRecipePhoto, analyzeUrl, analyzeText, ImportedRecipeData } from '../../../../api/recipeImport';
import { showAlert } from '../../../../utils/alert';

type Tab = 'photo' | 'url' | 'text';

type Props = {
  onAnalyzed: (data: ImportedRecipeData) => void;
};

// Calque `templates/recipe_import/index.html.twig` (panneau 0) / `recipe-import.js`
// (`btn-analyze`) — mêmes 3 sources (Photo/URL/texte), même endpoint d'analyse IA.
// Photo remplace l'ancien import PDF (demande utilisateur) : même `ImagePicker` que
// `ScanCameraView` (caméra directe ou galerie), sans prévisualisation caméra live —
// pas nécessaire pour une simple photo de page/fiche recette.
export function SourceStep({ onAnalyzed }: Props) {
  const [tab, setTab] = useState<Tab>('photo');
  const [photoUri, setPhotoUri] = useState<string | null>(null);
  const [url, setUrl] = useState('');
  const [text, setText] = useState('');
  const [analyzing, setAnalyzing] = useState(false);

  async function takePhoto() {
    const result = await ImagePicker.launchCameraAsync({ mediaTypes: ['images'], quality: 0.8 });
    if (result.canceled || !result.assets?.[0]) return;
    setPhotoUri(result.assets[0].uri);
  }

  async function pickPhotoFromGallery() {
    const mediaPermission = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (!mediaPermission.granted) {
      showAlert('Erreur', "L'accès à la galerie est nécessaire pour importer une photo.");
      return;
    }
    const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], quality: 0.8 });
    if (result.canceled || !result.assets?.[0]) return;
    setPhotoUri(result.assets[0].uri);
  }

  async function analyze() {
    setAnalyzing(true);
    try {
      let result;
      if (tab === 'photo') {
        if (!photoUri) { showAlert('Erreur', 'Veuillez prendre ou choisir une photo.'); return; }
        result = await analyzeRecipePhoto(photoUri);
      } else if (tab === 'url') {
        if (!url.trim()) { showAlert('Erreur', 'Veuillez saisir une URL.'); return; }
        result = await analyzeUrl(url.trim());
      } else {
        if (!text.trim()) { showAlert('Erreur', 'Veuillez saisir le texte de la recette.'); return; }
        result = await analyzeText(text.trim());
      }
      onAnalyzed(result.data);
    } catch (err) {
      showAlert('Erreur', err instanceof Error ? err.message : "Erreur lors de l'analyse.");
    } finally {
      setAnalyzing(false);
    }
  }

  return (
    <View style={styles.wrap}>
      <Text style={styles.h2}>D'où vient la recette ?</Text>
      <Text style={styles.help}>L'IA extrait et structure automatiquement la recette. Choisissez une source.</Text>

      <View style={styles.tabs}>
        {(['photo', 'text', 'url'] as Tab[]).map((t) => (
          <Pressable key={t} style={[styles.tab, tab === t && styles.tabOn]} onPress={() => setTab(t)}>
            <Text style={[styles.tabText, tab === t && styles.tabTextOn]}>
              {t === 'photo' ? 'Photo' : t === 'text' ? 'Texte libre' : 'URL'}
            </Text>
          </Pressable>
        ))}
      </View>

      {tab === 'photo' ? (
        photoUri ? (
          <Pressable style={styles.photoPreviewWrap} onPress={() => setPhotoUri(null)}>
            <Image source={{ uri: photoUri }} style={styles.photoPreview} />
            <View style={styles.photoPreviewBadge}>
              <Ionicons name="refresh" size={14} color="#fff" />
              <Text style={styles.photoPreviewBadgeText}>Changer de photo</Text>
            </View>
          </Pressable>
        ) : (
          <View style={styles.drop}>
            <Ionicons name="camera-outline" size={26} color={colors.primary} />
            <Text style={styles.dropTitle}>Photographiez votre recette</Text>
            <Text style={styles.dropHint}>Page de livre, fiche manuscrite, capture d'écran…</Text>
            <View style={styles.photoActions}>
              <Pressable style={styles.photoActionBtn} onPress={takePhoto}>
                <Ionicons name="camera" size={16} color={colors.primary} />
                <Text style={styles.photoActionText}>Prendre une photo</Text>
              </Pressable>
              <Pressable style={styles.photoActionBtn} onPress={pickPhotoFromGallery}>
                <Ionicons name="images" size={16} color={colors.primary} />
                <Text style={styles.photoActionText}>Depuis la galerie</Text>
              </Pressable>
            </View>
          </View>
        )
      ) : tab === 'text' ? (
        <View style={styles.field}>
          <Text style={styles.lbl}>Texte de la recette</Text>
          <Text style={styles.hint}>Ingrédients, quantités, étapes… collez tout, l'IA fait le tri.</Text>
          <TextInput
            style={styles.textarea}
            value={text}
            onChangeText={setText}
            placeholder="Ex. : Gratin dauphinois — 1,5 kg de pommes de terre, 1 L de lait…"
            placeholderTextColor={colors.textMuted}
            multiline
            numberOfLines={9}
          />
        </View>
      ) : (
        <View style={styles.field}>
          <Text style={styles.lbl}>Adresse de la page</Text>
          <Text style={styles.hint}>L'IA récupère et analyse le contenu de la page.</Text>
          <TextInput
            style={styles.input}
            value={url}
            onChangeText={setUrl}
            placeholder="https://exemple.com/recette/gratin-dauphinois"
            placeholderTextColor={colors.textMuted}
            autoCapitalize="none"
            keyboardType="url"
          />
        </View>
      )}

      <Pressable style={[styles.primaryBtn, analyzing && styles.primaryBtnDisabled]} disabled={analyzing} onPress={analyze}>
        {analyzing ? <ActivityIndicator color="#fff" /> : (
          <>
            <Ionicons name="sparkles" size={16} color="#fff" />
            <Text style={styles.primaryBtnText}>Analyser avec l'IA</Text>
          </>
        )}
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  wrap: { gap: spacing.sm },
  h2: { ...typography.title, fontSize: 20, color: colors.text },
  help: { ...typography.body, fontSize: 13.5, color: colors.textMuted, marginBottom: spacing.xs },
  tabs: { flexDirection: 'row', gap: spacing.xs, marginBottom: spacing.xs },
  tab: { flex: 1, alignItems: 'center', paddingVertical: spacing.sm, borderRadius: radii.md, borderWidth: 1, borderColor: colors.border, backgroundColor: colors.card },
  tabOn: { backgroundColor: '#eef0fe', borderColor: colors.primary },
  tabText: { fontSize: 13, fontWeight: '700', color: colors.textMuted },
  tabTextOn: { color: colors.primary },
  drop: { alignItems: 'center', gap: 6, borderWidth: 1.5, borderStyle: 'dashed', borderColor: colors.border, borderRadius: radii.md, padding: spacing.lg, backgroundColor: colors.card },
  dropTitle: { ...typography.body, fontSize: 14, fontWeight: '700', color: colors.text, textAlign: 'center' },
  dropHint: { ...typography.caption, fontSize: 12, color: colors.textMuted },
  photoActions: { flexDirection: 'row', gap: spacing.xs, marginTop: spacing.xs },
  photoActionBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 6, paddingHorizontal: spacing.sm, paddingVertical: spacing.xs + 2,
    borderRadius: radii.sm, borderWidth: 1, borderColor: colors.primary, backgroundColor: '#fff',
  },
  photoActionText: { ...typography.caption, fontSize: 13, fontWeight: '700', color: colors.primary },
  photoPreviewWrap: { borderRadius: radii.md, overflow: 'hidden', backgroundColor: colors.card },
  photoPreview: { width: '100%', aspectRatio: 1.4 },
  photoPreviewBadge: {
    position: 'absolute', bottom: spacing.sm, alignSelf: 'center', flexDirection: 'row', alignItems: 'center', gap: 6,
    paddingHorizontal: spacing.sm, paddingVertical: 6, borderRadius: radii.pill, backgroundColor: 'rgba(0,0,0,0.55)',
  },
  photoPreviewBadgeText: { color: '#fff', fontWeight: '700', fontSize: 12.5 },
  field: { gap: 4 },
  lbl: { fontSize: 13, fontWeight: '700', color: colors.text },
  hint: { ...typography.caption, fontSize: 12, color: colors.textMuted, marginBottom: 2 },
  input: { borderWidth: 1, borderColor: colors.border, borderRadius: radii.sm, paddingHorizontal: spacing.sm, paddingVertical: spacing.sm + 2, color: colors.text, backgroundColor: colors.card },
  textarea: {
    borderWidth: 1, borderColor: colors.border, borderRadius: radii.sm, padding: spacing.sm, color: colors.text,
    backgroundColor: colors.card, minHeight: 160, textAlignVertical: 'top',
  },
  primaryBtn: { flexDirection: 'row', gap: 8, marginTop: spacing.xs, paddingVertical: spacing.sm + 4, borderRadius: radii.sm, backgroundColor: colors.primary, alignItems: 'center', justifyContent: 'center' },
  primaryBtnDisabled: { opacity: 0.5 },
  primaryBtnText: { color: '#fff', fontWeight: '700', fontSize: 14.5 },
});
