"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";
//  新增：导入 user API
import { fetchUserDetails } from "@/app/api/user/actions";
import { fetchNameList } from "@/app/api/user/actions";

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

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

  useEffect(() => {
    if (!isActive && scanningMode) {
      stopScanning();
    }
  }, [isActive]);

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

  const stopScanning = (): void => {
    setScanningMode(false);
    setScanError(null);
    onDeactivate?.();
  };

  const handleOperatorScan = async (
    e: React.KeyboardEvent<HTMLInputElement>,
  ): Promise<void> => {
    const target = e.target as HTMLInputElement;
    let usernameInput: string = target.value.trim();

    if (e.key === "Enter" || usernameInput.endsWith("}")) {
      console.log("Raw input:", usernameInput);
      
      try {
        //  检查是否是测试快捷格式 {2fitest<id>}
        const testMatch = usernameInput.match(/\{2fitest(\d+)\??}?/i);
        if (testMatch && testMatch[1]) {
          const userId = parseInt(testMatch[1]);
          console.log(`🧪 Test mode: Fetching user with ID ${userId} from API`);
          
          try {
            //  方案 1：使用 fetchNameList 获取所有用户，然后找到对应 ID
            const nameList = await fetchNameList();
            const matchedUser = nameList.find(user => user.id === userId);
            
            if (matchedUser) {
              //  将 NameList 转换为 Operator 格式
              const operator: Operator = {
                id: matchedUser.id,
                name: matchedUser.name,
                username: `user${matchedUser.id}`, // 生成一个 username
              };
              
              const isAlreadyAdded = operators.some(
                (op) => op.id === operator.id,
              );
              
              if (!isAlreadyAdded) {
                onOperatorsChange([...operators, operator]);
              }
              
              target.value = "";
              setScanError(null);
              console.log(` Added operator from API:`, operator);
              return;
            } else {
              setScanError(
                `User with ID ${userId} not found. Please check the ID and try again.`
              );
              target.value = "";
              return;
            }
          } catch (apiError) {
            console.error("Error fetching user by ID:", apiError);
            setScanError(
              "Failed to fetch user data. Please try again."
            );
            target.value = "";
            return;
          }
        }
        
        let username: string;
        
        //  尝试解析 JSON
        try {
          const usernameObj: OperatorQrCode = JSON.parse(usernameInput);
          username = usernameObj.username;
        } catch (jsonError) {
          //  如果不是 JSON，尝试从花括号中提取
          const match = usernameInput.match(/\{([^}?]+)\??}?/);
          if (match && match[1]) {
            username = match[1].trim();
            console.log("Extracted username from braces:", username);
          } else {
            //  如果没有花括号，直接使用输入值
            username = usernameInput.replace(/[{}?]/g, '').trim();
            console.log("Using plain username:", username);
          }
        }

        if (!username) {
          setScanError("Invalid input format");
          return;
        }

        const response = await isOperatorExist(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);
        } 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" }}
            />
            <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. Test format: {"{2fitest<id>"} (e.g., {"{2fitest1}"})
            </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">
                ID: {operator.id} | Username: {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;