"use client";
import React, { useState, useRef } from 'react';
import { Operator } from './types';
import { Button, TextField, Typography, Paper, Box, IconButton, Stack } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';

interface OperatorScannerProps {
  operators: Operator[];
  onOperatorsChange: (operators: Operator[]) => void;
  error?: string;
}

const operatorDatabase: Operator[] = [
  { id: 1, name: 'John Smith', employeeId: 'EMP001', cardId: '12345678' },
  { id: 2, name: 'Maria Garcia', employeeId: 'EMP002', cardId: '23456789' },
  { id: 3, name: 'David Chen', employeeId: 'EMP003', cardId: '34567890' },
  { id: 4, name: 'Sarah Johnson', employeeId: 'EMP004', cardId: '45678901' },
  { id: 5, name: 'Mike Wilson', employeeId: 'EMP005', cardId: '56789012' }
];

const OperatorScanner: React.FC<OperatorScannerProps> = ({ 
  operators, 
  onOperatorsChange, 
  error 
}) => {
  const [scanningMode, setScanningMode] = useState<boolean>(false);
  const operatorScanRef = useRef<HTMLInputElement>(null);

  const startScanning = (): void => {
    setScanningMode(true);
    setTimeout(() => {
      if (operatorScanRef.current) {
        operatorScanRef.current.focus();
      }
    }, 100);
  };

  const stopScanning = (): void => {
    setScanningMode(false);
  };

  const handleOperatorScan = (e: React.KeyboardEvent<HTMLInputElement>): void => {
    if (e.key === 'Enter') {
      const target = e.target as HTMLInputElement;
      const scannedId = target.value.trim();
      const operator = operatorDatabase.find(op => 
        op.cardId === scannedId || op.employeeId === scannedId
      );
      
      if (operator) {
        const isAlreadyAdded = operators.some(op => op.id === operator.id);
        
        if (!isAlreadyAdded) {
          onOperatorsChange([...operators, operator]);
        }
        
        target.value = '';
        stopScanning();
      } else {
        alert('Operator not found. Please check the ID and try again.');
        target.value = '';
      }
    }
  };

  const removeOperator = (operatorId: number): void => {
    onOperatorsChange(operators.filter(op => op.id !== operatorId));
  };

  return (
    <Box>
      <Stack direction="row" alignItems="center" justifyContent="space-between" mb={2}>
        <Typography variant="h6" fontWeight={600}>
          Operators *
        </Typography>
        <Button
          variant={scanningMode ? 'contained' : 'outlined'}
          color={scanningMode ? 'success' : 'primary'}
          onClick={startScanning}
        >
          {scanningMode ? 'Scanning...' : 'Scan ID Card'}
        </Button>
      </Stack>

      {scanningMode && (
        <Paper elevation={2} sx={{ mb: 2, p: 2, bgcolor: 'green.50', border: '1px solid', borderColor: 'green.200' }}>
          <Stack direction="row" alignItems="center" spacing={2}>
            <TextField
              inputRef={operatorScanRef}
              type="text"
              onKeyPress={handleOperatorScan}
              fullWidth
              label="Scan operator ID card or enter manually..."
              variant="outlined"
              size="small"
              sx={{ bgcolor: 'white' }}
            />
            <Button
              variant="contained"
              color="inherit"
              onClick={stopScanning}
            >
              Cancel
            </Button>
          </Stack>
          <Typography variant="body2" color="success.main" mt={1}>
            Position the ID card scanner and scan, or type the employee ID manually
          </Typography>
        </Paper>
      )}

      {error && <Typography color="error" variant="body2" mb={1}>{error}</Typography>}

      <Stack spacing={1}>
        {operators.map((operator) => (
          <Paper key={operator.id} sx={{ p: 2, display: 'flex', alignItems: 'center', justifyContent: 'space-between', bgcolor: 'blue.50', border: '1px solid', borderColor: 'blue.200' }}>
            <Box>
              <Typography fontWeight={500} color="primary.dark">{operator.name}</Typography>
              <Typography variant="body2" color="primary.main">{operator.employeeId}</Typography>
            </Box>
            <IconButton onClick={() => removeOperator(operator.id)} color="error">
              <CloseIcon />
            </IconButton>
          </Paper>
        ))}
        {operators.length === 0 && (
          <Paper sx={{ p: 2, bgcolor: 'grey.100', border: '1px solid', borderColor: 'grey.200' }}>
            <Typography color="text.secondary" fontStyle="italic" variant="body2">
              No operators added yet. Use the scan button to add operators.
            </Typography>
          </Paper>
        )}
      </Stack>
    </Box>
  );
};

export default OperatorScanner;