import { useRef, useState } from 'react';
import { View, Text, StyleSheet, Pressable, ActivityIndicator, Platform } from 'react-native';
import { CameraView, useCameraPermissions } from 'expo-camera';
import * as ImagePicker from 'expo-image-picker';
import Ionicons from '@expo/vector-icons/Ionicons';
import { decodeBarcodeFromUri } from '../utils/barcodeDecoder';
import { colors, spacing, radii, typography } from '../theme';

// Écran caméra partagé entre `PhotoCaptureModal` (suivi) et `ProductScanModal`
// (produits) — même interface de scan dans les deux flux (CLAUDE.md
// "Factoriser") ; seul ce qui se passe APRÈS (lookup Open Food Facts, analyse
// IA, recherche food-lookup...) reste propre à chaque appelant, via les
// callbacks `onBarcodeFound`/`onPhotoCaptured`.
//
// Mode barcode : scan live natif (`expo-camera`). Sur web, qui ne détecte en
// live que les QR codes (`ExpoCamera.web.tsx`), pas de prévisualisation caméra
// dans la page : on délègue à l'appareil photo natif de l'OS via
// `ImagePicker.launchCameraAsync` (input file `capture="environment"`), comme
// le faisait déjà `assets/js/food-lookup.js` (web Twig historique) — une vraie
// photo native (mise au point, résolution) décode nettement mieux avec ZXing
// qu'un instantané de flux vidéo `getUserMedia` capturé sur un `<canvas>`,
// utilisé un temps ici et peu fiable au décodage (essayé et abandonné, cf.
// `.wolf/cerebrum.md`). Décodage via `decodeBarcodeFromUri` (ZXing sur web,
// `expo-camera` `scanFromURLAsync` en natif). Un bouton "importer une image"
// est proposé dans les deux cas, décodé par la même fonction.
// Mode photo : shutter + import galerie, l'URI est renvoyée telle quelle à
// l'appelant qui gère lui-même l'identification.

export type ScanCameraMode = 'barcode' | 'photo';

type Props = {
  mode: ScanCameraMode;
  onBarcodeFound: (barcode: string) => void;
  onPhotoCaptured: (uri: string) => void;
  photoHint?: string;
  permissionDeniedText?: string;
};

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

const BARCODE_TYPES = ['ean13', 'ean8', 'upc_a', 'upc_e'] as const;

export function ScanCameraView({
  mode,
  onBarcodeFound,
  onPhotoCaptured,
  photoHint = 'Photographiez, ou importez une photo',
  permissionDeniedText = "L'accès à la caméra est nécessaire.",
}: Props) {
  const [permission, requestPermission] = useCameraPermissions();
  const [screen, setScreen] = useState<Screen>({ kind: 'scan' });
  const cameraRef = useRef<CameraView>(null);
  const scanLockRef = useRef(false);

  function handleBarcodeScanned({ data }: { data: string }) {
    if (scanLockRef.current) return;
    scanLockRef.current = true;
    onBarcodeFound(data);
  }

  async function decodeAndReport(uri: string) {
    setScreen({ kind: 'decoding' });
    const code = await decodeBarcodeFromUri(uri);
    if (code) {
      onBarcodeFound(code);
    } else {
      setScreen({ kind: 'error', message: 'Code-barres non détecté. Recadrez-le bien visible, à plat, sans reflet ni doigt dessus.' });
    }
  }

  async function handleCaptureBarcodeWeb() {
    const result = await ImagePicker.launchCameraAsync({ mediaTypes: ['images'], cameraType: ImagePicker.CameraType.back, quality: 1 });
    if (!result.canceled) await decodeAndReport(result.assets[0].uri);
  }

  async function handleTakePhoto() {
    const photo = await cameraRef.current?.takePictureAsync({ quality: 0.6 });
    if (photo) onPhotoCaptured(photo.uri);
  }

  async function pickFromGallery(onUri: (uri: string) => void, quality = 0.8) {
    const mediaPermission = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (!mediaPermission.granted) {
      setScreen({ kind: 'error', message: "L'accès à la galerie est nécessaire pour importer une image." });
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], quality });
    if (result.canceled) return;
    onUri(result.assets[0].uri);
  }

  const isWebBarcode = Platform.OS === 'web' && mode === 'barcode';

  return (
    <View style={styles.wrap}>
      {isWebBarcode && screen.kind === 'scan' && (
        <View style={styles.center}>
          <Ionicons name="barcode-outline" size={48} color={colors.textMuted} />
          <Text style={styles.scanHintDark}>Photographiez le code-barres, ou importez une image</Text>
          <Pressable style={styles.actionButton} onPress={handleCaptureBarcodeWeb}>
            <Text style={styles.actionButtonText}>Photographier le code-barres</Text>
          </Pressable>
          <Pressable onPress={() => pickFromGallery(decodeAndReport, 1)}>
            <Text style={styles.linkText}>Importer une image depuis la galerie</Text>
          </Pressable>
        </View>
      )}

      {!isWebBarcode && !permission && (
        <View style={styles.center}>
          <ActivityIndicator color={colors.primary} />
        </View>
      )}

      {!isWebBarcode && permission && !permission.granted && (
        <View style={styles.center}>
          <Ionicons name="camera-outline" size={40} color={colors.textMuted} />
          <Text style={styles.permissionText}>{permissionDeniedText}</Text>
          <Pressable style={styles.actionButton} onPress={requestPermission}>
            <Text style={styles.actionButtonText}>Autoriser la caméra</Text>
          </Pressable>
          <Pressable onPress={() => pickFromGallery(mode === 'barcode' ? decodeAndReport : onPhotoCaptured, mode === 'barcode' ? 1 : 0.8)}>
            <Text style={styles.linkText}>Importer une image depuis la galerie</Text>
          </Pressable>
        </View>
      )}

      {!isWebBarcode && permission?.granted && screen.kind === 'scan' && mode === 'barcode' && (
        <View style={styles.cameraWrap}>
          <CameraView
            ref={cameraRef}
            style={StyleSheet.absoluteFill}
            facing="back"
            barcodeScannerSettings={{ barcodeTypes: [...BARCODE_TYPES] }}
            onBarcodeScanned={handleBarcodeScanned}
          />
          <View pointerEvents="none" style={styles.scanOverlay}>
            <View style={styles.scanFrame} />
            <Text style={styles.scanHint}>Visez un code-barres, ou importez une image</Text>
          </View>
          <Pressable style={styles.galleryButton} onPress={() => pickFromGallery(decodeAndReport, 1)} hitSlop={8}>
            <Ionicons name="images" size={24} color="#fff" />
          </Pressable>
        </View>
      )}

      {permission?.granted && screen.kind === 'scan' && mode === 'photo' && (
        <View style={styles.cameraWrap}>
          <CameraView ref={cameraRef} style={StyleSheet.absoluteFill} facing="back" />
          <View pointerEvents="none" style={styles.scanOverlay}>
            <Text style={styles.scanHint}>{photoHint}</Text>
          </View>
          <Pressable style={styles.shutter} onPress={handleTakePhoto}>
            <Ionicons name="camera" size={28} color="#fff" />
          </Pressable>
          <Pressable style={styles.galleryButton} onPress={() => pickFromGallery(onPhotoCaptured)} hitSlop={8}>
            <Ionicons name="images" size={24} color="#fff" />
          </Pressable>
        </View>
      )}

      {screen.kind === 'decoding' && (
        <View style={styles.center}>
          <ActivityIndicator color={colors.primary} size="large" />
          <Text style={styles.loadingText}>Lecture du code-barres…</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>
  );
}

const styles = StyleSheet.create({
  wrap: { flex: 1 },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: spacing.md, padding: spacing.xl },
  permissionText: { ...typography.body, color: colors.textMuted, textAlign: 'center' },
  actionButton: { backgroundColor: colors.primary, borderRadius: radii.md, paddingHorizontal: spacing.lg, paddingVertical: spacing.sm },
  actionButtonText: { ...typography.body, color: '#fff', fontWeight: '700' },
  linkText: { ...typography.caption, color: colors.primary, fontWeight: '700' },
  cameraWrap: { flex: 1, margin: spacing.lg, borderRadius: radii.lg, overflow: 'hidden', backgroundColor: '#000' },
  scanOverlay: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: spacing.md, padding: spacing.lg },
  scanFrame: { width: '75%', aspectRatio: 1.6, borderWidth: 3, borderColor: 'rgba(255,255,255,0.85)', borderRadius: radii.md },
  scanHint: { ...typography.caption, color: '#fff', textAlign: 'center', backgroundColor: 'rgba(0,0,0,0.4)', padding: spacing.sm, borderRadius: radii.sm },
  scanHintDark: { ...typography.body, color: colors.textMuted, textAlign: 'center' },
  shutter: {
    position: 'absolute',
    bottom: spacing.lg,
    alignSelf: 'center',
    width: 64,
    height: 64,
    borderRadius: 32,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
  },
  galleryButton: {
    position: 'absolute',
    bottom: spacing.lg + 8,
    right: spacing.lg,
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: 'rgba(0,0,0,0.45)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  loadingText: { ...typography.body, color: colors.textMuted },
  errorText: { ...typography.body, color: colors.text, textAlign: 'center' },
});
