import { useEffect, useState } from "react";
import * as SecureStore from "expo-secure-store";
import { Camera, PermissionResponse } from "expo-camera";
import { BarCodeScannerResult } from "expo-barcode-scanner";
import { router } from "expo-router";

export const useQRScanner = () => {
  const [status, requestPermission] = Camera.useCameraPermissions();
  const [hasPermission, setHasPermission] = useState<boolean>(false);
  const [qrData, setQRData] = useState<string | null>(null);
  const [scanning, setScanning] = useState<boolean>(qrData === null);
  const getPermission = async () => {
    const permission = await requestPermission();
    if (permission.granted) {
      setHasPermission(true);
    }
  };

  const onQRScanned = (data: BarCodeScannerResult) => {
    console.log(data.data);
    setQRData(data.data);
    setScanning(false);
    router.back();
    router.push(data.data);
  };
  useEffect(() => {
    if (status?.granted) {
      setHasPermission(true);
    }
  }, [status]);
  return { hasPermission, getPermission, scanning, qrData, onQRScanned};
};
