"use client";

import {
  Box,
  Button,
  Stack,
  TextField,
  Typography,
  Alert,
  CircularProgress,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  TablePagination,
  Modal,
} from "@mui/material";
import React, { useCallback, useEffect, useState, useRef, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useRouter } from "next/navigation";
import {
  fetchAllPickOrderLotsHierarchicalWorkbench,
  updateStockOutLineStatus,
  createStockOutLine,
  recordPickExecutionIssue,
  fetchFGPickOrdersByUserIdWorkbench,
  FGPickOrderResponse, 
  autoAssignAndReleasePickOrder, 
  AutoAssignReleaseResponse,
  checkPickOrderCompletion,
  PickOrderCompletionResponse,
  checkAndCompletePickOrderByConsoCode,
  fetchDoPickOrderDetail,
  DoPickOrderDetail,
  batchQrSubmit,
} from "@/app/api/pickOrder/actions";
import { fetchNameList, NameList } from "@/app/api/user/actions";
import {
  FormProvider,
  useForm,
} from "react-hook-form";
import SearchBox, { Criterion } from "@/components/SearchBox";
import { CreateStockOutLine } from "@/app/api/pickOrder/actions";
import { updateInventoryLotLineQuantities } from "@/app/api/inventory/actions";
import QrCodeIcon from '@mui/icons-material/QrCode';
import { useQrCodeScannerContext } from "@/components/QrCodeScannerProvider/QrCodeScannerProvider";
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig";
import { fetchStockInLineInfo } from "@/app/api/po/actions";
import GoodPickExecutionForm from "@/components/FinishedGoodSearch/GoodPickExecutionForm";
import FGPickOrderCard from "@/components/FinishedGoodSearch/FGPickOrderCard";
import WorkbenchFloorLanePanel from "./WorkbenchFloorLanePanel";
import FGPickOrderInfoCard from "@/components/FinishedGoodSearch/FGPickOrderInfoCard";
export type GoodPickExecutionFloorPanelProps = {
  onPickOrderAssigned?: () => void;
  onSwitchToDetailTab?: () => void;
  initialReleaseType?: string;
};

interface Props {
  filterArgs: Record<string, any>;
  onFgPickOrdersChange?: (fgPickOrders: FGPickOrderResponse[]) => void;
  onSwitchToDetailTab?: () => void;
  onFirstLoadDone?: () => void;
}

//  QR Code Modal Component (from LotTable)
const QrCodeModal: React.FC<{
  open: boolean;
  onClose: () => void;
  lot: any | null;
  onQrCodeSubmit: (lotNo: string) => void;
  combinedLotData: any[]; //  Add this prop
}> = ({ open, onClose, lot, onQrCodeSubmit, combinedLotData }) => {
  const { t } = useTranslation("pickOrder");
  const { values: qrValues, isScanning, startScan, stopScan, resetScan } = useQrCodeScannerContext();
  const [manualInput, setManualInput] = useState<string>('');
  const floorPanelTimerStartedRef = useRef(false);
  const [manualInputSubmitted, setManualInputSubmitted] = useState<boolean>(false);
  const [manualInputError, setManualInputError] = useState<boolean>(false);
  const [isProcessingQr, setIsProcessingQr] = useState<boolean>(false);
  const [qrScanFailed, setQrScanFailed] = useState<boolean>(false);
  const [qrScanSuccess, setQrScanSuccess] = useState<boolean>(false);
  
  const [processedQrCodes, setProcessedQrCodes] = useState<Set<string>>(new Set());
  const [scannedQrResult, setScannedQrResult] = useState<string>('');
  const [fgPickOrder, setFgPickOrder] = useState<FGPickOrderResponse | null>(null);
  // Process scanned QR codes
  useEffect(() => {
    if (qrValues.length > 0 && lot && !isProcessingQr && !qrScanSuccess) {
      const latestQr = qrValues[qrValues.length - 1];
      
      if (processedQrCodes.has(latestQr)) {
        console.log("QR code already processed, skipping...");
        return;
      }
      
      setProcessedQrCodes(prev => new Set(prev).add(latestQr));
      
      try {
        const qrData = JSON.parse(latestQr);
        
        if (qrData.stockInLineId && qrData.itemId) {
          setIsProcessingQr(true);
          setQrScanFailed(false);
          
          fetchStockInLineInfo(qrData.stockInLineId)
            .then((stockInLineInfo) => {
              console.log("Stock in line info:", stockInLineInfo);
              setScannedQrResult(stockInLineInfo.lotNo || 'Unknown lot number');
              
              if (stockInLineInfo.lotNo === lot.lotNo) {
                console.log(` QR Code verified for lot: ${lot.lotNo}`);
                setQrScanSuccess(true);
                onQrCodeSubmit(lot.lotNo);
                onClose();
                resetScan();
              } else {
                console.log(`❌ QR Code mismatch. Expected: ${lot.lotNo}, Got: ${stockInLineInfo.lotNo}`);
                setQrScanFailed(true);
                setManualInputError(true);
                setManualInputSubmitted(true);
              }
            })
            .catch((error) => {
              console.error("Error fetching stock in line info:", error);
              setScannedQrResult('Error fetching data');
              setQrScanFailed(true);
              setManualInputError(true);
              setManualInputSubmitted(true);
            })
            .finally(() => {
              setIsProcessingQr(false);
            });
        } else {
          const qrContent = latestQr.replace(/[{}]/g, '');
          setScannedQrResult(qrContent);
          
          if (qrContent === lot.lotNo) {
            setQrScanSuccess(true);
            onQrCodeSubmit(lot.lotNo);
            onClose();
            resetScan();
          } else {
            setQrScanFailed(true);
            setManualInputError(true);
            setManualInputSubmitted(true);
          }
        }
      } catch (error) {
        console.log("QR code is not JSON format, trying direct comparison");
        const qrContent = latestQr.replace(/[{}]/g, '');
        setScannedQrResult(qrContent);
        
        if (qrContent === lot.lotNo) {
          setQrScanSuccess(true);
          onQrCodeSubmit(lot.lotNo);
          onClose();
          resetScan();
        } else {
          setQrScanFailed(true);
          setManualInputError(true);
          setManualInputSubmitted(true);
        }
      }
    }
  }, [qrValues, lot, onQrCodeSubmit, onClose, resetScan, isProcessingQr, qrScanSuccess, processedQrCodes]);

  // Clear states when modal opens
  useEffect(() => {
    if (open) {
      setManualInput('');
      setManualInputSubmitted(false);
      setManualInputError(false);
      setIsProcessingQr(false);
      setQrScanFailed(false);
      setQrScanSuccess(false);
      setScannedQrResult('');
      setProcessedQrCodes(new Set());
    }
  }, [open]);

  useEffect(() => {
    if (lot) {
      setManualInput('');
      setManualInputSubmitted(false);
      setManualInputError(false);
      setIsProcessingQr(false);
      setQrScanFailed(false);
      setQrScanSuccess(false);
      setScannedQrResult('');
      setProcessedQrCodes(new Set());
    }
  }, [lot]);

  // Auto-submit manual input when it matches
  useEffect(() => {
    if (manualInput.trim() === lot?.lotNo && manualInput.trim() !== '' && !qrScanFailed && !qrScanSuccess) {
      console.log(' Auto-submitting manual input:', manualInput.trim());
      
      const timer = setTimeout(() => {
        setQrScanSuccess(true);
        onQrCodeSubmit(lot.lotNo);
        onClose();
        setManualInput('');
        setManualInputError(false);
        setManualInputSubmitted(false);
      }, 200);
      
      return () => clearTimeout(timer);
    }
  }, [manualInput, lot, onQrCodeSubmit, onClose, qrScanFailed, qrScanSuccess]);

  const handleManualSubmit = () => {
    if (manualInput.trim() === lot?.lotNo) {
      setQrScanSuccess(true);
      onQrCodeSubmit(lot.lotNo);
      onClose();
      setManualInput('');
    } else {
      setQrScanFailed(true);
      setManualInputError(true);
      setManualInputSubmitted(true);
    }
  };

  useEffect(() => {
    if (open) {
      startScan();
    }
  }, [open, startScan]);

  return (
    <Modal open={open} onClose={onClose}>
      <Box sx={{
        position: 'absolute',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        bgcolor: 'background.paper',
        p: 3,
        borderRadius: 2,
        minWidth: 400,
      }}>
        <Typography variant="h6" gutterBottom>
          {t("QR Code Scan for Lot")}: {lot?.lotNo}
        </Typography>
        
        {isProcessingQr && (
          <Box sx={{ mb: 2, p: 2, backgroundColor: '#e3f2fd', borderRadius: 1 }}>
            <Typography variant="body2" color="primary">
               {t("Processing QR code...")}
            </Typography>
          </Box>
        )}
        
        <Box sx={{ mb: 2 }}>
          <Typography variant="body2" gutterBottom>
            <strong>{t("Manual Input")}:</strong>
          </Typography>
          <TextField
            fullWidth
            size="small"
            value={manualInput}
            onChange={(e) => {
              setManualInput(e.target.value);
              if (qrScanFailed || manualInputError) {
                setQrScanFailed(false);
                setManualInputError(false);
                setManualInputSubmitted(false);
              }
            }}
            sx={{ mb: 1 }}
            error={manualInputSubmitted && manualInputError}
            helperText={
              manualInputSubmitted && manualInputError
                ? `${t("The input is not the same as the expected lot number.")}`
                : ''
            }
          />
          <Button
            variant="contained"
            onClick={handleManualSubmit}
            disabled={!manualInput.trim()}
            size="small"
            color="primary"
          >
            {t("Submit")}
          </Button>
        </Box>

        {qrValues.length > 0 && (
          <Box sx={{ 
            mb: 2, 
            p: 2, 
            backgroundColor: qrScanFailed ? '#ffebee' : qrScanSuccess ? '#e8f5e8' : '#f5f5f5', 
            borderRadius: 1 
          }}>
            <Typography variant="body2" color={qrScanFailed ? 'error' : qrScanSuccess ? 'success' : 'text.secondary'}>
              <strong>{t("QR Scan Result:")}</strong> {scannedQrResult}
            </Typography>

            {qrScanSuccess && (
              <Typography variant="caption" color="success" display="block">
                 {t("Verified successfully!")}
              </Typography>
            )}
          </Box>
        )}

        <Box sx={{ mt: 2, textAlign: 'right' }}>
          <Button onClick={onClose} variant="outlined">
            {t("Cancel")}
          </Button>
        </Box>
      </Box>
    </Modal>
  );
};

const WorkbenchGoodPickExecution: React.FC<Props> = ({
  filterArgs,
  onFgPickOrdersChange,
  onSwitchToDetailTab,
  onFirstLoadDone,
}) => {
  const FloorPanel = WorkbenchFloorLanePanel;
  const { t } = useTranslation("pickOrder");
  const router = useRouter();
  const { data: session } = useSession() as { data: SessionWithTokens | null };
  
  const currentUserId = session?.id ? parseInt(session.id) : undefined;
  
  const [combinedLotData, setCombinedLotData] = useState<any[]>([]);
  const [combinedDataLoading, setCombinedDataLoading] = useState(false);
  const [originalCombinedData, setOriginalCombinedData] = useState<any[]>([]);
  
  const { values: qrValues, isScanning, startScan, stopScan, resetScan } = useQrCodeScannerContext();
  const [doPickOrderDetail, setDoPickOrderDetail] = useState<DoPickOrderDetail | null>(null);
const [selectedPickOrderId, setSelectedPickOrderId] = useState<number | null>(null);
const [pickOrderSwitching, setPickOrderSwitching] = useState(false);
  const [qrScanInput, setQrScanInput] = useState<string>('');
  const [qrScanError, setQrScanError] = useState<boolean>(false);
  const [qrScanSuccess, setQrScanSuccess] = useState<boolean>(false);
  
  const [pickQtyData, setPickQtyData] = useState<Record<string, number>>({});
  const [searchQuery, setSearchQuery] = useState<Record<string, any>>({});

  const [paginationController, setPaginationController] = useState({
    pageNum: 0,
    pageSize: 10,
  });

  const [usernameList, setUsernameList] = useState<NameList[]>([]);

  const initializationRef = useRef(false);
  const autoAssignRef = useRef(false);

  const formProps = useForm();
  const errors = formProps.formState.errors;

  //  Add QR modal states
  const [qrModalOpen, setQrModalOpen] = useState(false);
  const [selectedLotForQr, setSelectedLotForQr] = useState<any | null>(null);
  const floorPanelTimerStartedRef = useRef(false);
  //  Add GoodPickExecutionForm states
  const [pickExecutionFormOpen, setPickExecutionFormOpen] = useState(false);
  const [selectedLotForExecutionForm, setSelectedLotForExecutionForm] = useState<any | null>(null);
  const [fgPickOrders, setFgPickOrders] = useState<FGPickOrderResponse[]>([]);
  const [fgPickOrdersLoading, setFgPickOrdersLoading] = useState(false);
// 在 GoodPickExecutiondetail.tsx 中修改 fetchFgPickOrdersData
// 修改 fetchFgPickOrdersData 函数：
const fetchFgPickOrdersData = useCallback(async () => {
  if (!currentUserId) return;
  
  setFgPickOrdersLoading(true);
  try {
    const fgPickOrders = await fetchFGPickOrdersByUserIdWorkbench(currentUserId);
    
    console.log("🔍 DEBUG: Fetched FG pick orders:", fgPickOrders);
    console.log("🔍 DEBUG: First order numberOfPickOrders:", fgPickOrders[0]?.numberOfPickOrders);
    
    setFgPickOrders(fgPickOrders);

    if (onFgPickOrdersChange) {
      onFgPickOrdersChange(fgPickOrders);
    }

    
  } catch (error) {
    console.error("❌ Error fetching FG pick orders:", error);
    setFgPickOrders([]);

    if (onFgPickOrdersChange) {
      onFgPickOrdersChange([]);
    }
    
  } finally {
    setFgPickOrdersLoading(false);
  }
}, [currentUserId, selectedPickOrderId]);
  
  //  简化：移除复杂的 useEffect 依赖
  useEffect(() => {
    if (currentUserId) {
      fetchFgPickOrdersData();
    }
  }, [currentUserId, fetchFgPickOrdersData]);

  //  Handle QR code button click
  const handleQrCodeClick = (pickOrderId: number) => {
    console.log(`QR Code clicked for pick order ID: ${pickOrderId}`);
    // TODO: Implement QR code functionality
  };

  useEffect(() => {
    startScan();
    return () => {
      stopScan();
      resetScan();
    };
  }, [startScan, stopScan, resetScan]);

  const fetchAllCombinedLotData = useCallback(async (userId?: number) => {
    setCombinedDataLoading(true);
    try {
      const userIdToUse = userId || currentUserId;
      
      console.log(" fetchAllCombinedLotData called with userId:", userIdToUse);
      
      if (!userIdToUse) {
        console.warn("⚠️ No userId available, skipping API call");
        setCombinedLotData([]);
        setOriginalCombinedData([]);
        return;
      }
      
      // ✅ Fix: fetchAllPickOrderLotsHierarchical returns hierarchical data, not a flat array
      const hierarchicalData = await fetchAllPickOrderLotsHierarchicalWorkbench(userIdToUse);
      console.log(" Hierarchical data:", hierarchicalData);
      
      // ✅ Fix: Ensure we always set an array
      // If hierarchicalData is not in the expected format, default to empty array
      let allLotDetails: any[] = [];
      
      if (hierarchicalData && Array.isArray(hierarchicalData)) {
        // If it's already an array, use it directly
        allLotDetails = hierarchicalData;
      } else if (hierarchicalData?.pickOrders && Array.isArray(hierarchicalData.pickOrders)) {
        // Process hierarchical data into flat array (similar to GoodPickExecutiondetail.tsx)
        const mergedPickOrder = hierarchicalData.pickOrders[0];
        if (mergedPickOrder?.pickOrderLines) {
          mergedPickOrder.pickOrderLines.forEach((line: any) => {
            if (line.lots && line.lots.length > 0) {
              line.lots.forEach((lot: any) => {
                allLotDetails.push({
                  pickOrderConsoCode: mergedPickOrder.consoCode,
                  pickOrderTargetDate: mergedPickOrder.targetDate,
                  pickOrderStatus: mergedPickOrder.status,
                  pickOrderId: line.pickOrderId || mergedPickOrder.pickOrderIds?.[0] || 0,
                  pickOrderCode: mergedPickOrder.pickOrderCodes?.[0] || "",
                  pickOrderLineId: line.id,
                  pickOrderLineRequiredQty: line.requiredQty,
                  pickOrderLineStatus: line.status,
                  itemId: line.item?.id,
                  itemCode: line.item?.code,
                  itemName: line.item?.name,
                  uomDesc: line.item?.uomDesc,
                  uomShortDesc: line.item?.uomShortDesc,
                  lotId: lot.id,
                  lotNo: lot.lotNo,
                  expiryDate: lot.expiryDate,
                  location: lot.location,
                  stockUnit: lot.stockUnit,
                  availableQty: lot.availableQty,
                  requiredQty: lot.requiredQty,
                  actualPickQty: lot.actualPickQty,
                  lotStatus: lot.lotStatus,
                  lotAvailability: lot.lotAvailability,
                  processingStatus: lot.processingStatus,
                  stockOutLineId: lot.stockOutLineId,
                  stockOutLineStatus: lot.stockOutLineStatus,
                  stockOutLineQty: lot.stockOutLineQty,
                  routerId: lot.router?.id,
                  routerIndex: lot.router?.index,
                  routerRoute: lot.router?.route,
                  routerArea: lot.router?.area,
                });
              });
            }
          });
        }
      }
      
      console.log(" All combined lot details:", allLotDetails);
      setCombinedLotData(allLotDetails);
      setOriginalCombinedData(allLotDetails);
      
      // ✅ Fix: Add safety check - ensure allLotDetails is an array before using .every()
      const allCompleted = Array.isArray(allLotDetails) && allLotDetails.length > 0 && allLotDetails.every((lot: any) => 
        lot.processingStatus === 'completed'
      );
      
      //  发送完成状态事件，包含标签页信息
      window.dispatchEvent(new CustomEvent('pickOrderCompletionStatus', {
        detail: { 
          allLotsCompleted: allCompleted,
          tabIndex: 0 //  明确指定这是来自标签页 0 的事件
        }
      }));
      
    } catch (error) {
      console.error("❌ Error fetching combined lot data:", error);
      setCombinedLotData([]);
      setOriginalCombinedData([]);
      
      //  如果加载失败，禁用打印按钮
      window.dispatchEvent(new CustomEvent('pickOrderCompletionStatus', {
        detail: { 
          allLotsCompleted: false,
          tabIndex: 0
        }
      }));
    } finally {
      setCombinedDataLoading(false);
    }
  }, [currentUserId, combinedLotData]);


  //  Only fetch existing data when session is ready, no auto-assignment
  useEffect(() => {
    if (session && currentUserId && !initializationRef.current) {
      console.log(" Session loaded, initializing pick order...");
      initializationRef.current = true;
  
      (async () => {
        try {
          await fetchAllCombinedLotData();    // ✅ 等待数据加载完成
        } finally {
          if (onFirstLoadDone) {
            onFirstLoadDone();               // ✅ 这时候再结束 [FinishedGoodSearch] page ready
          }
        }
      })();
    }
  }, [session, currentUserId, fetchAllCombinedLotData, onFirstLoadDone]);
  //  Add event listener for manual assignment
  useEffect(() => {
    const handlePickOrderAssigned = () => {
      console.log("🔄 Pick order assigned event received, refreshing data...");
      fetchAllCombinedLotData();
    };

    window.addEventListener('pickOrderAssigned', handlePickOrderAssigned);
    
    return () => {
      window.removeEventListener('pickOrderAssigned', handlePickOrderAssigned);
    };
  }, [fetchAllCombinedLotData]);

  //  Handle QR code submission for matched lot (external scanning)
   //  Handle QR code submission for matched lot (external scanning)
   /*
   const handleQrCodeSubmit = useCallback(async (lotNo: string) => {
    console.log(` Processing QR Code for lot: ${lotNo}`);
    
    //  Use current data without refreshing to avoid infinite loop
    const currentLotData = combinedLotData;
    console.log(`🔍 Available lots:`, currentLotData.map(lot => lot.lotNo));
    
    const matchingLots = currentLotData.filter(lot => 
      lot.lotNo === lotNo || 
      lot.lotNo?.toLowerCase() === lotNo.toLowerCase()
    );
    
    if (matchingLots.length === 0) {
      console.error(`❌ Lot not found: ${lotNo}`);
      setQrScanError(true);
      setQrScanSuccess(false);
      return; 
    }
    
    console.log(` Found ${matchingLots.length} matching lots:`, matchingLots);
    setQrScanError(false);
    
    try {
      let successCount = 0;
      let existsCount = 0;
      let errorCount = 0;
      
      for (const matchingLot of matchingLots) {
        console.log(`🔄 Processing pick order line ${matchingLot.pickOrderLineId} for lot ${lotNo}`);
        
        if (matchingLot.stockOutLineId) {
          console.log(` Stock out line already exists for line ${matchingLot.pickOrderLineId}`);
          existsCount++;
        } else {
          const stockOutLineData: CreateStockOutLine = {
            consoCode: matchingLot.pickOrderConsoCode,
            pickOrderLineId: matchingLot.pickOrderLineId,
            inventoryLotLineId: matchingLot.lotId,
            qty: 0.0
          };
          
          console.log(`Creating stock out line for pick order line ${matchingLot.pickOrderLineId}:`, stockOutLineData);
          const result = await createStockOutLine(stockOutLineData);
          console.log(`Create stock out line result for line ${matchingLot.pickOrderLineId}:`, result);
          
          if (result && result.code === "EXISTS") {
            console.log(` Stock out line already exists for line ${matchingLot.pickOrderLineId}`);
            existsCount++;
          } else if (result && result.code === "SUCCESS") {
            console.log(` Stock out line created successfully for line ${matchingLot.pickOrderLineId}`);
            successCount++;
          } else {
            console.error(`❌ Failed to create stock out line for line ${matchingLot.pickOrderLineId}:`, result);
            errorCount++;
          }
        }
      }
      
      //  Always refresh data after processing (success or failure)
      console.log("🔄 Refreshing data after QR code processing...");
      await fetchAllCombinedLotData();
      
      if (successCount > 0 || existsCount > 0) {
        console.log(` QR Code processing completed: ${successCount} created, ${existsCount} already existed`);
        setQrScanSuccess(true);
        setQrScanInput(''); // Clear input after successful processing
        
        //  Clear success state after a delay
        setTimeout(() => {
          setQrScanSuccess(false);
        }, 2000);
      } else {
        console.error(`❌ QR Code processing failed: ${errorCount} errors`);
        setQrScanError(true);
        setQrScanSuccess(false);
        
        //  Clear error state after a delay
        setTimeout(() => {
          setQrScanError(false);
        }, 3000);
      }
    } catch (error) {
      console.error("❌ Error processing QR code:", error);
      setQrScanError(true);
      setQrScanSuccess(false);
      
      //  Still refresh data even on error
      await fetchAllCombinedLotData();
      
      //  Clear error state after a delay
      setTimeout(() => {
        setQrScanError(false);
      }, 3000);
    }
  }, [combinedLotData, fetchAllCombinedLotData]);
  */  const handleQrCodeSubmit = useCallback(async (lotNo: string) => {
    console.log(` Processing QR Code for lot: ${lotNo}`);
    
    //  Use current data without refreshing to avoid infinite loop
    const currentLotData = combinedLotData;
    console.log(`🔍 Available lots:`, currentLotData.map(lot => lot.lotNo));
    
    const matchingLots = currentLotData.filter(lot => 
      lot.lotNo === lotNo || 
      lot.lotNo?.toLowerCase() === lotNo.toLowerCase()
    );
    
    if (matchingLots.length === 0) {
      console.error(`❌ Lot not found: ${lotNo}`);
      setQrScanError(true);
      setQrScanSuccess(false);
      return; 
    }
    
    console.log(` Found ${matchingLots.length} matching lots:`, matchingLots);
    setQrScanError(false);
    
    try {
      let successCount = 0;
      let existsCount = 0;
      let errorCount = 0;
      
      for (const matchingLot of matchingLots) {
        console.log(`🔄 Processing pick order line ${matchingLot.pickOrderLineId} for lot ${lotNo}`);
        
        if (matchingLot.stockOutLineId) {
          console.log(` Stock out line already exists for line ${matchingLot.pickOrderLineId}`);
          existsCount++;
        } else {
          const stockOutLineData: CreateStockOutLine = {
            consoCode: matchingLot.pickOrderConsoCode,
            pickOrderLineId: matchingLot.pickOrderLineId,
            inventoryLotLineId: matchingLot.lotId,
            qty: 0.0
          };
          
          console.log(`Creating stock out line for pick order line ${matchingLot.pickOrderLineId}:`, stockOutLineData);
          const result = await createStockOutLine(stockOutLineData);
          console.log(`Create stock out line result for line ${matchingLot.pickOrderLineId}:`, result);
          
          if (result && result.code === "EXISTS") {
            console.log(` Stock out line already exists for line ${matchingLot.pickOrderLineId}`);
            existsCount++;
          } else if (result && result.code === "SUCCESS") {
            console.log(` Stock out line created successfully for line ${matchingLot.pickOrderLineId}`);
            successCount++;
          } else {
            console.error(`❌ Failed to create stock out line for line ${matchingLot.pickOrderLineId}:`, result);
            errorCount++;
          }
        }
      }
      
      //  Always refresh data after processing (success or failure)
      console.log("🔄 Refreshing data after QR code processing...");
      await fetchAllCombinedLotData();
      
      if (successCount > 0 || existsCount > 0) {
        console.log(` QR Code processing completed: ${successCount} created, ${existsCount} already existed`);
        setQrScanSuccess(true);
        setQrScanInput(''); // Clear input after successful processing
        
        //  Clear success state after a delay
        setTimeout(() => {
          setQrScanSuccess(false);
        }, 2000);
      } else {
        console.error(`❌ QR Code processing failed: ${errorCount} errors`);
        setQrScanError(true);
        setQrScanSuccess(false);
        
        //  Clear error state after a delay
        setTimeout(() => {
          setQrScanError(false);
        }, 3000);
      }
    } catch (error) {
      console.error("❌ Error processing QR code:", error);
      setQrScanError(true);
      setQrScanSuccess(false);
      
      //  Still refresh data even on error
      await fetchAllCombinedLotData();
      
      //  Clear error state after a delay
      setTimeout(() => {
        setQrScanError(false);
      }, 3000);
    }
  }, [combinedLotData, fetchAllCombinedLotData]);

  const handleManualInputSubmit = useCallback(() => {
    if (qrScanInput.trim() !== '') {
      handleQrCodeSubmit(qrScanInput.trim());
    }
  }, [qrScanInput, handleQrCodeSubmit]);

  //  Handle QR code submission from modal (internal scanning)
  const handleQrCodeSubmitFromModal = useCallback(async (lotNo: string) => {
    if (selectedLotForQr && selectedLotForQr.lotNo === lotNo) {
      console.log(` QR Code verified for lot: ${lotNo}`);
      
      const requiredQty = selectedLotForQr.requiredQty;
      const lotId = selectedLotForQr.lotId;
      
      // Create stock out line
      const stockOutLineData: CreateStockOutLine = {
        consoCode: selectedLotForQr.pickOrderConsoCode, //  Use pickOrderConsoCode instead of pickOrderCode
        pickOrderLineId: selectedLotForQr.pickOrderLineId,
        inventoryLotLineId: selectedLotForQr.lotId,
        qty: 0.0
      };
      
      try {
        await createStockOutLine(stockOutLineData);
        console.log("Stock out line created successfully!");
        
        // Close modal
        setQrModalOpen(false);
        setSelectedLotForQr(null);
        
        // Set pick quantity
        const lotKey = `${selectedLotForQr.pickOrderLineId}-${lotId}`;
        setTimeout(() => {
          setPickQtyData(prev => ({
            ...prev,
            [lotKey]: requiredQty
          }));
          console.log(` Auto-set pick quantity to ${requiredQty} for lot ${lotNo}`);
        }, 500);
        
        // Refresh data
        await fetchAllCombinedLotData();
      } catch (error) {
        console.error("Error creating stock out line:", error);
      }
    }
  }, [selectedLotForQr, fetchAllCombinedLotData]);

  //  Outside QR scanning - process QR codes from outside the page automatically
  useEffect(() => {
    if (qrValues.length > 0 && combinedLotData.length > 0) {
      const latestQr = qrValues[qrValues.length - 1];
      
      // Extract lot number from QR code
      let lotNo = '';
      try {
        const qrData = JSON.parse(latestQr);
        if (qrData.stockInLineId && qrData.itemId) {
          // For JSON QR codes, we need to fetch the lot number
          fetchStockInLineInfo(qrData.stockInLineId)
            .then((stockInLineInfo) => {
              console.log("Outside QR scan - Stock in line info:", stockInLineInfo);
              const extractedLotNo = stockInLineInfo.lotNo;
              if (extractedLotNo) {
                console.log(`Outside QR scan detected (JSON): ${extractedLotNo}`);
                handleQrCodeSubmit(extractedLotNo);
              }
            })
            .catch((error) => {
              console.error("Outside QR scan - Error fetching stock in line info:", error);
            });
          return; // Exit early for JSON QR codes
        }
      } catch (error) {
        // Not JSON format, treat as direct lot number
        lotNo = latestQr.replace(/[{}]/g, '');
      }
      
      // For direct lot number QR codes
      if (lotNo) {
        console.log(`Outside QR scan detected (direct): ${lotNo}`);
        handleQrCodeSubmit(lotNo);
      }
    }
  }, [qrValues, combinedLotData, handleQrCodeSubmit]);

  useEffect(() => {
    if (typeof window === "undefined") return;
  
    const key = "__FG_FLOOR_PANEL_TIMER_STARTED__" as const;
  
    // 只有当「没有 FG 订单」时才会显示 FinishedGoodFloorLanePanel
    if (fgPickOrders.length === 0 && !fgPickOrdersLoading) {
      if (!(window as any)[key]) {
        (window as any)[key] = true;
        console.time("[FG] FloorLanePanel initial load");
      }
    }
  
    // 如果之后拿到 FG 订单，你可以选择在这里清掉标记（可选）
    if (fgPickOrders.length > 0 && (window as any)[key]) {
      // delete (window as any)[key];
    }
  }, [fgPickOrders.length, fgPickOrdersLoading]);
  const handlePickQtyChange = useCallback((lotKey: string, value: number | string) => {
    if (value === '' || value === null || value === undefined) {
      setPickQtyData(prev => ({
        ...prev,
        [lotKey]: 0
      }));
      return;
    }
    
    const numericValue = typeof value === 'string' ? parseFloat(value) : value;
    
    if (isNaN(numericValue)) {
      setPickQtyData(prev => ({
        ...prev,
        [lotKey]: 0
      }));
      return;
    }
    
    setPickQtyData(prev => ({
      ...prev,
      [lotKey]: numericValue
    }));
  }, []);

  const [autoAssignStatus, setAutoAssignStatus] = useState<'idle' | 'checking' | 'assigned' | 'no_orders'>('idle');
  const [autoAssignMessage, setAutoAssignMessage] = useState<string>('');
  const [completionStatus, setCompletionStatus] = useState<PickOrderCompletionResponse | null>(null);

  const checkAndAutoAssignNext = useCallback(async () => {
    if (!currentUserId) return;
    
    try {
      const completionResponse = await checkPickOrderCompletion(currentUserId);
      
      if (completionResponse.code === "SUCCESS" && completionResponse.entity?.hasCompletedOrders) {
        console.log("Found completed pick orders, auto-assigning next...");
        //  移除前端的自动分配逻辑，因为后端已经处理了
        // await handleAutoAssignAndRelease(); // 删除这个函数
      }
    } catch (error) {
      console.error("Error checking pick order completion:", error);
    }
  }, [currentUserId]);

  //  Handle submit pick quantity
  const handleSubmitPickQty = useCallback(async (lot: any) => {
    const lotKey = `${lot.pickOrderLineId}-${lot.lotId}`;
    const newQty = pickQtyData[lotKey] || 0;
    
    if (!lot.stockOutLineId) {
      console.error("No stock out line found for this lot");
      return;
    }
    
    try {
      const currentActualPickQty = lot.actualPickQty || 0;
      const cumulativeQty = currentActualPickQty + newQty;
      
      let newStatus = 'partially_completed';
      
      if (cumulativeQty >= lot.requiredQty) {
        newStatus = 'completed';
      }
      
      console.log(`=== PICK QUANTITY SUBMISSION DEBUG ===`);
      console.log(`Lot: ${lot.lotNo}`);
      console.log(`Required Qty: ${lot.requiredQty}`);
      console.log(`Current Actual Pick Qty: ${currentActualPickQty}`);
      console.log(`New Submitted Qty: ${newQty}`);
      console.log(`Cumulative Qty: ${cumulativeQty}`);
      console.log(`New Status: ${newStatus}`);
      console.log(`=====================================`);
      
      await updateStockOutLineStatus({
        id: lot.stockOutLineId,
        status: newStatus,
        qty: cumulativeQty
      });
      
      if (newQty > 0) {
        await updateInventoryLotLineQuantities({
          inventoryLotLineId: lot.lotId,
          qty: newQty,
          status: 'available',
          operation: 'pick'
        });
      }
      
      //  FIXED: Use the proper API function instead of direct fetch
      if (newStatus === 'completed' && lot.pickOrderConsoCode) {
        console.log(` Lot ${lot.lotNo} completed, checking if pick order ${lot.pickOrderConsoCode} is complete...`);
        
        try {
          //  Use the imported API function instead of direct fetch
          const completionResponse = await checkAndCompletePickOrderByConsoCode(lot.pickOrderConsoCode);
          console.log(` Pick order completion check result:`, completionResponse);
          
          if (completionResponse.code === "SUCCESS") {
            console.log(`�� Pick order ${lot.pickOrderConsoCode} completed successfully!`);
          } else if (completionResponse.message === "not completed") {
            console.log(`⏳ Pick order not completed yet, more lines remaining`);
          } else {
            console.error(`❌ Error checking completion: ${completionResponse.message}`);
          }
        } catch (error) {
          console.error("Error checking pick order completion:", error);
        }
      }
      
      await fetchAllCombinedLotData();
      console.log("Pick quantity submitted successfully!");
      
      setTimeout(() => {
        checkAndAutoAssignNext();
      }, 1000);
      
    } catch (error) {
      console.error("Error submitting pick quantity:", error);
    }
  }, [pickQtyData, fetchAllCombinedLotData, checkAndAutoAssignNext]);

  //  Handle reject lot
  const handleRejectLot = useCallback(async (lot: any) => {
    if (!lot.stockOutLineId) {
      console.error("No stock out line found for this lot");
      return;
    }
  
    try {
      await updateStockOutLineStatus({
        id: lot.stockOutLineId,
        status: 'rejected',
        qty: 0
      });
      
      await fetchAllCombinedLotData();
      console.log("Lot rejected successfully!");
      
      setTimeout(() => {
        checkAndAutoAssignNext();
      }, 1000);
      
    } catch (error) {
      console.error("Error rejecting lot:", error);
    }
  }, [fetchAllCombinedLotData, checkAndAutoAssignNext]);

  //  Handle pick execution form
  const handlePickExecutionForm = useCallback((lot: any) => {
    console.log("=== Pick Execution Form ===");
    console.log("Lot data:", lot);
    
    if (!lot) {
      console.warn("No lot data provided for pick execution form");
      return;
    }
    
    console.log("Opening pick execution form for lot:", lot.lotNo);
    
    setSelectedLotForExecutionForm(lot);
    setPickExecutionFormOpen(true);
    
    console.log("Pick execution form opened for lot ID:", lot.lotId);
  }, []);

  const handlePickExecutionFormSubmit = useCallback(async (data: any) => {
    try {
        console.log("Pick execution form submitted:", data);
        const issueData = {
          ...data,
          type: "Do",  // Delivery Order Record 类型
        };
        const result = await recordPickExecutionIssue(issueData);
      console.log("Pick execution issue recorded:", result);
      
      if (result && result.code === "SUCCESS") {
        console.log(" Pick execution issue recorded successfully");
      } else {
        console.error("❌ Failed to record pick execution issue:", result);
      }
      
      setPickExecutionFormOpen(false);
      setSelectedLotForExecutionForm(null);
      
      await fetchAllCombinedLotData();
    } catch (error) {
      console.error("Error submitting pick execution form:", error);
    }
  }, [fetchAllCombinedLotData]);

  //  Calculate remaining required quantity
  const calculateRemainingRequiredQty = useCallback((lot: any) => {
    const requiredQty = lot.requiredQty || 0;
    const stockOutLineQty = lot.stockOutLineQty || 0;
    return Math.max(0, requiredQty - stockOutLineQty);
  }, []);

  // Search criteria
  const searchCriteria: Criterion<any>[] = [
    {
      label: t("Pick Order Code"),
      paramName: "pickOrderCode",
      type: "text",
    },
      {
        label: t("Item Code"),
        paramName: "itemCode",
        type: "text",
      },
      {
        label: t("Item Name"),
        paramName: "itemName",
        type: "text",
      },
      {
      label: t("Lot No"),
      paramName: "lotNo",
      type: "text",
    },
  ];

  const handleSearch = useCallback((query: Record<string, any>) => {
    setSearchQuery({ ...query });
    console.log("Search query:", query);

    if (!originalCombinedData) return;

    const filtered = originalCombinedData.filter((lot: any) => {
      const pickOrderCodeMatch = !query.pickOrderCode || 
        lot.pickOrderCode?.toLowerCase().includes((query.pickOrderCode || "").toLowerCase());
      
        const itemCodeMatch = !query.itemCode || 
        lot.itemCode?.toLowerCase().includes((query.itemCode || "").toLowerCase());
        
        const itemNameMatch = !query.itemName || 
        lot.itemName?.toLowerCase().includes((query.itemName || "").toLowerCase());
      
      const lotNoMatch = !query.lotNo || 
        lot.lotNo?.toLowerCase().includes((query.lotNo || "").toLowerCase());
      
      return pickOrderCodeMatch && itemCodeMatch && itemNameMatch && lotNoMatch;
    });
    
    setCombinedLotData(filtered);
    console.log("Filtered lots count:", filtered.length);
  }, [originalCombinedData]);

  const handleReset = useCallback(() => {
    setSearchQuery({});
    if (originalCombinedData) {
      setCombinedLotData(originalCombinedData);
    }
  }, [originalCombinedData]);

  const handlePageChange = useCallback((event: unknown, newPage: number) => {
    setPaginationController(prev => ({
      ...prev,
      pageNum: newPage,
    }));
  }, []);

  const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    const newPageSize = parseInt(event.target.value, 10);
    setPaginationController({
      pageNum: 0,
      pageSize: newPageSize,
    });
  }, []);

  const paginatedData = useMemo(() => {
    // ✅ Fix: Add safety check to ensure combinedLotData is an array
    if (!Array.isArray(combinedLotData)) {
      console.warn(" combinedLotData is not an array:", combinedLotData);
      return [];
    }
    
    //  Sort by routerIndex first, then by other criteria
    const sortedData = [...combinedLotData].sort((a: any, b: any) => {
      const aIndex = a.routerIndex || 0;
      const bIndex = b.routerIndex || 0;
      
      // Primary sort: by routerIndex
      if (aIndex !== bIndex) {
        return aIndex - bIndex;
      }
      
      // Secondary sort: by pickOrderCode if routerIndex is the same
      if (a.pickOrderCode !== b.pickOrderCode) {
        return a.pickOrderCode.localeCompare(b.pickOrderCode);
      }
      
      // Tertiary sort: by lotNo if everything else is the same
      return (a.lotNo || '').localeCompare(b.lotNo || '');
    });
    
    const startIndex = paginationController.pageNum * paginationController.pageSize;
    const endIndex = startIndex + paginationController.pageSize;
    return sortedData.slice(startIndex, endIndex);
  }, [combinedLotData, paginationController]);
return (
  <FormProvider {...formProps}>
    {/*  修复：改进条件渲染逻辑 */}
    {combinedDataLoading || fgPickOrdersLoading ? (
      //  数据加载中，显示加载指示器
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
        <CircularProgress />
      </Box>
    ) : fgPickOrders.length === 0 ? (
      //  没有活动订单，显示楼层选择面板
      <FloorPanel
        onPickOrderAssigned={() => {
          if (currentUserId) {
            fetchAllCombinedLotData(currentUserId);
            fetchFgPickOrdersData();
          }
        }}
        onSwitchToDetailTab={onSwitchToDetailTab}
      />
    ) : (
      //  有活动订单，显示 FG 订单信息
      <Box>
  {fgPickOrders.map((fgOrder) => (
    <Box key={fgOrder.pickOrderId} sx={{ mb: 2 }}>
      <FGPickOrderInfoCard
        fgOrder={fgOrder}
      />
      

    </Box>
  ))}
</Box>
    )}
    
    {/* Modals */}
    <QrCodeModal
      open={qrModalOpen}
      onClose={() => setQrModalOpen(false)}
      lot={selectedLotForQr}
      onQrCodeSubmit={handleQrCodeSubmit}
      combinedLotData={combinedLotData}
    />
    
    <GoodPickExecutionForm
      open={pickExecutionFormOpen}
      onClose={() => {
        setPickExecutionFormOpen(false);
        setSelectedLotForExecutionForm(null);
      }}
      onSubmit={handlePickExecutionFormSubmit}
      selectedLot={selectedLotForExecutionForm}
      selectedPickOrderLine={null}
      pickOrderId={selectedLotForExecutionForm?.pickOrderId}
      pickOrderCreateDate={null}
    />
  </FormProvider>
);
};

export default WorkbenchGoodPickExecution;