"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<OperatorScannerProps> = ({
  operators,
  onOperatorsChange,
  error,
}) => {
  const [scanningMode, setScanningMode] = useState<boolean>(false);
  const [scanError, setScanError] = useState<string | null>(null);
  const operatorScanRef = useRef<HTMLInputElement>(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<HTMLInputElement>,
  ): Promise<void> => {
    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 (
    <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"
              onKeyDown={handleOperatorScan}
              fullWidth
              label="Scan operator ID card or enter manually..."
              variant="outlined"
              size="small"
              sx={{ bgcolor: "white" }}
              onInput={handleOperatorScan}
            />
            <Button variant="contained" color="inherit" onClick={stopScanning}>
              Cancel
            </Button>
          </Stack>
          {scanError ? (
            <Typography variant="body2" color="error" mt={1}>
              {scanError}
            </Typography>
          ) : (
            <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.username}
              </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;
