import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import { useRouter } from 'expo-router';
import { BarcodeScanner } from '../components/BarcodeScanner';
import { searchMedicines } from '../services/medicines';

export default function ScannerScreen() {
  const router = useRouter();
  const [isSearching, setIsSearching] = useState(false);

  const handleBarcodeScanned = async (barcode: string) => {
    setIsSearching(true);
    try {
      const results = await searchMedicines(barcode);
      if (results.length > 0) {
        router.push(`/medicine/${results[0].nregistro}`);
      } else {
        router.push(`/medicine/${barcode}`);
      }
    } catch (error) {
      console.error('Error searching medicine:', error);
      router.push(`/medicine/${barcode}`);
    } finally {
      setIsSearching(false);
    }
  };

  const handleClose = () => {
    router.back();
  };

  return (
    <View style={styles.container}>
      <BarcodeScanner
        onBarcodeScanned={handleBarcodeScanned}
        onClose={handleClose}
      />
    </View>
  );
}

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