import { useEffect, useState } from "react";

export function useDetectBarcode() {
  const [barcode, setBarcode] = useState<string>("");
  const [lastBarcode, setLastBarcode] = useState<string>("");

  useEffect(() => {
    let interval: any;

    const handleKeydown = (evt: any) => {
      if (interval) clearInterval(interval);

      if (evt.code === "Enter") {
        if (barcode) handleBarcode(barcode);
        setBarcode("");
        return;
      }

      if (evt.key !== "Shift") setBarcode((prev) => prev + evt.key);

      interval = setInterval(() => setBarcode(""), 20);
    };

    // Adding the event listener when the component mounts
    document.addEventListener("keydown", handleKeydown);

    // Cleanup the event listener when the component unmounts
    return () => {
      document.removeEventListener("keydown", handleKeydown);
      if (interval) clearInterval(interval);
    };
  }, [barcode]);

  const handleBarcode = (scannedBarcode: string) => {
    setLastBarcode(scannedBarcode);
  };

  return lastBarcode;
}
