"use client"; import React, { useState, useRef, useEffect } from 'react'; import { Operator } from "@/app/api/jo"; import { Button, TextField, Typography, Paper, Box, IconButton, Stack } from '@mui/material'; import CloseIcon from '@mui/icons-material/Close'; import { isOperatorExist } from '@/app/api/jo/actions'; import { OperatorQrCode } from './types'; interface OperatorScannerProps { operators: Operator[]; onOperatorsChange: (operators: Operator[]) => void; error?: string; } const OperatorScanner: React.FC = ({ operators, onOperatorsChange, error }) => { const [scanningMode, setScanningMode] = useState(false); const [scanError, setScanError] = useState(null); const operatorScanRef = useRef(null); const startScanning = (): void => { setScanningMode(true); setScanError(null); setTimeout(() => { if (operatorScanRef.current) { operatorScanRef.current.focus(); } }, 100); }; const stopScanning = (): void => { setScanningMode(false); setScanError(null); }; const handleOperatorScan = async (e: React.KeyboardEvent): Promise => { const target = e.target as HTMLInputElement; const usernameJSON: string = target.value.trim(); if (e.key === 'Enter' || usernameJSON.endsWith('}') ) { console.log(usernameJSON) try { const usernameObj: OperatorQrCode = JSON.parse(usernameJSON) const response = await isOperatorExist(usernameObj.username) if (response.message === "Success") { const isAlreadyAdded = operators.some(op => op.username === response.entity.username); if (!isAlreadyAdded) { onOperatorsChange([...operators, response.entity]); } target.value = ''; setScanError(null); // stopScanning(); } else { setScanError('Operator not found. Please check the ID and try again.'); target.value = ''; } } catch (error) { console.error('Error checking operator:', error); setScanError('An error occurred while checking the operator. Please try again.'); target.value = ''; } } }; const removeOperator = (operatorId: number): void => { onOperatorsChange(operators.filter(op => op.id !== operatorId)); }; return ( Operators * {scanningMode && ( {scanError ? ( {scanError} ) : ( Position the ID card scanner and scan, or type the employee ID manually )} )} {error && {error}} {operators.map((operator) => ( {operator.name} {operator.username} removeOperator(operator.id)} color="error"> ))} {operators.length === 0 && ( No operators added yet. Use the scan button to add operators. )} ); }; export default OperatorScanner;