import React from "react";
import { Alert, StyleSheet, View } from "react-native";
import type { NativeStackScreenProps } from "@react-navigation/native-stack";
import { LabelCamera } from "../components/LabelCamera";
import { LoadingView } from "../components/LoadingView";
import { useProduct } from "../hooks/useProduct";
import type { RootStackParamList } from "../navigation/types";

type Props = NativeStackScreenProps<RootStackParamList, "LabelScanner">;

export function LabelScannerScreen({ navigation }: Props) {
  const { loadByLabelImage, loading } = useProduct();

  const handleCapture = async (uri: string) => {
    const product = await loadByLabelImage(uri);
    if (!product) {
      Alert.alert(
        "Etiqueta no reconocida",
        "No encontramos una botella similar. Probá de nuevo con mejor luz o más cerca.",
      );
      return;
    }
    navigation.replace("Bottle");
  };

  if (loading) {
    return <LoadingView message="Buscando etiqueta..." />;
  }

  return (
    <View style={styles.container}>
      <LabelCamera onCapture={(uri) => void handleCapture(uri)} busy={loading} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
});
