import { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Pressable, Modal, ActivityIndicator } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { identifyFoodPhoto } from '../../../api/foodLookup';
import { ScanCameraView } from '../../../components/ScanCameraView';
import { colors, spacing, radii, typography } from '../../../theme';

// L'écran de scan/photo (caméra, permission, import galerie) est factorisé dans
// `ScanCameraView`, partagé avec `PhotoCaptureModal` (suivi) — même interface
// dans les deux flux. Ce composant ne gère que ce qui suit la capture :
// identification IA de l'aliment photographié (le lookup du code-barres est
// géré par l'écran parent, `FoodLookupScreen`, via `onBarcodeFound`).

type Props = {
  visible: boolean;
  mode: 'barcode' | 'photo';
  onClose: () => void;
  onBarcodeFound: (barcode: string) => void;
  onPhotoIdentified: (name: string) => void;
};

type Screen = { kind: 'scan' } | { kind: 'identifying' } | { kind: 'error'; message: string };

export function ProductScanModal({ visible, mode, onClose, onBarcodeFound, onPhotoIdentified }: Props) {
  const [screen, setScreen] = useState<Screen>({ kind: 'scan' });

  useEffect(() => {
    if (visible) setScreen({ kind: 'scan' });
  }, [visible, mode]);

  async function handlePhotoCaptured(uri: string) {
    setScreen({ kind: 'identifying' });
    try {
      const { name } = await identifyFoodPhoto(uri);
      onPhotoIdentified(name);
    } catch (e) {
      setScreen({ kind: 'error', message: e instanceof Error ? e.message : 'Identification impossible.' });
    }
  }

  return (
    <Modal visible={visible} animationType="slide" onRequestClose={onClose} presentationStyle="fullScreen">
      <View style={styles.root}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>{mode === 'barcode' ? 'Scanner un code-barres' : 'Photographier un aliment'}</Text>
          <Pressable onPress={onClose} hitSlop={12}>
            <Ionicons name="close" size={24} color={colors.text} />
          </Pressable>
        </View>

        {screen.kind === 'scan' && (
          <ScanCameraView
            mode={mode}
            onBarcodeFound={onBarcodeFound}
            onPhotoCaptured={handlePhotoCaptured}
            photoHint="Photographiez l'aliment, ou importez une photo"
            permissionDeniedText="L'accès à la caméra est nécessaire pour scanner un produit."
          />
        )}

        {screen.kind === 'identifying' && (
          <View style={styles.center}>
            <ActivityIndicator color={colors.primary} size="large" />
            <Text style={styles.loadingText}>Identification de l'aliment…</Text>
          </View>
        )}

        {screen.kind === 'error' && (
          <View style={styles.center}>
            <Ionicons name="alert-circle-outline" size={40} color={colors.danger} />
            <Text style={styles.errorText}>{screen.message}</Text>
            <Pressable style={styles.actionButton} onPress={() => setScreen({ kind: 'scan' })}>
              <Text style={styles.actionButtonText}>Réessayer</Text>
            </Pressable>
          </View>
        )}
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  root: { flex: 1, backgroundColor: colors.background },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.lg,
    paddingBottom: spacing.sm,
  },
  headerTitle: { ...typography.body, fontWeight: '700', fontSize: 17, color: colors.text },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: spacing.md, padding: spacing.xl },
  actionButton: { backgroundColor: colors.primary, borderRadius: radii.md, paddingHorizontal: spacing.lg, paddingVertical: spacing.sm },
  actionButtonText: { ...typography.body, color: '#fff', fontWeight: '700' },
  loadingText: { ...typography.body, color: colors.textMuted },
  errorText: { ...typography.body, color: colors.text, textAlign: 'center' },
});
