"use client";
import { PickOrderResult } from "@/app/api/pickOrder";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import SearchBox, { Criterion } from "../SearchBox";
import {
  flatten,
  intersectionWith,
  isEmpty,
  sortBy,
  uniqBy,
  upperCase,
} from "lodash";
import {
  arrayToDayjs,
} from "@/app/utils/formatUtil";
import { Button, Grid, Stack, Tab, Tabs, TabsProps, Typography, Box, TextField } from "@mui/material";
import PickOrders from "./FinishedGood";
import ConsolidatedPickOrders from "./ConsolidatedPickOrders";
import PickExecution from "./GoodPickExecution";
import CreatePickOrderModal from "./CreatePickOrderModal";
import NewCreateItem from "./newcreatitem";
import AssignAndRelease from "./AssignAndRelease";
import AssignTo from "./assignTo";
import { fetchAllItemsInClient, ItemCombo } from "@/app/api/settings/item/actions";
import { fetchPickOrderClient, autoAssignAndReleasePickOrder, autoAssignAndReleasePickOrderByStore, fetchReleasedDoPickOrders } from "@/app/api/pickOrder/actions";
import Jobcreatitem from "./Jobcreatitem";
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig";
//import PickExecutionDetail from "./GoodPickExecutiondetail";
import GoodPickExecutionRecord from "./GoodPickExecutionRecord";
import Swal from "sweetalert2";
import { printDN, printDNLabels } from "@/app/api/do/actions";
import { FGPickOrderResponse, fetchStoreLaneSummary, assignByLane,type StoreLaneSummary   } from "@/app/api/pickOrder/actions";
import FGPickOrderCard from "./FGPickOrderCard";
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import dayjs, { Dayjs } from 'dayjs';
import { PrinterCombo } from "@/app/api/settings/printer";
import { Autocomplete } from "@mui/material";
import FGPickOrderTicketReleaseTable from "./FGPickOrderTicketReleaseTable";
import TruckRoutingSummaryTab, { TruckRoutingSummaryFilters } from "./TruckRoutingSummaryTab";
import FinishedGoodCartonDashboardTab from "./FinishedGoodCartonDashboardTab";
import { clientAuthFetch } from "@/app/utils/clientAuthFetch";
import { NEXT_PUBLIC_API_URL } from "@/config/api";
import { fetchTruckRoutingSummaryPrecheck } from "@/app/(main)/report/truckRoutingSummaryApi";
import {
  FEATURE_USAGE,
  FEATURE_USAGE_ACTION,
  logFeatureUsage,
} from "@/lib/featureUsageLog";

interface Props {
 // pickOrders: PickOrderResult[];
  printerCombo: PrinterCombo[];
}

type SearchQuery = Partial<
  Omit<PickOrderResult, "id" | "consoCode" | "completeDate">
>;

type SearchParamNames = keyof SearchQuery;

const PickOrderSearch: React.FC<Props> = ({ printerCombo }) => {
  const { t } = useTranslation("pickOrder");
  const { data: session } = useSession() as { data: SessionWithTokens | null };
  const currentUserId = session?.id ? parseInt(session.id) : undefined;

  const [isOpenCreateModal, setIsOpenCreateModal] = useState(false)
  const [items, setItems] = useState<ItemCombo[]>([])
  const [printButtonsEnabled, setPrintButtonsEnabled] = useState(false);
  //const [filteredPickOrders, setFilteredPickOrders] = useState(pickOrders);
  const [filterArgs, setFilterArgs] = useState<Record<string, any>>({});
  const [searchQuery, setSearchQuery] = useState<Record<string, any>>({}); 
  const [tabIndex, setTabIndex] = useState(0);
  const [totalCount, setTotalCount] = useState<number>();
  const [isAssigning, setIsAssigning] = useState(false);
 // const [summary2F, setSummary2F] = useState<StoreLaneSummary | null>(null);
 // const [summary4F, setSummary4F] = useState<StoreLaneSummary | null>(null);
  const [isLoadingSummary, setIsLoadingSummary] = useState(false);

  const [selectedPrinterForAllDraft, setSelectedPrinterForAllDraft] = useState<PrinterCombo | null>(null);
const [selectedPrinterForDraft, setSelectedPrinterForDraft] = useState<PrinterCombo | null>(null);
  const [selectedPrinterForRecord, setSelectedPrinterForRecord] = useState<PrinterCombo | null>(null);
  const [truckRoutingFilters, setTruckRoutingFilters] = useState<TruckRoutingSummaryFilters>({
    storeId: "",
    truckLanceCode: "",
    date: "",
  });
  const [isPrintingRoutingSummary, setIsPrintingRoutingSummary] = useState(false);



  const [hideCompletedUntilNext, setHideCompletedUntilNext] = useState<boolean>(
    typeof window !== 'undefined' && localStorage.getItem('hideCompletedUntilNext') === 'true'
  );

  const [fgPickOrdersData, setFgPickOrdersData] = useState<FGPickOrderResponse[]>([]);
  useEffect(() => {
    if (typeof window === "undefined") return;
  
    const key = "__FG_PAGE_READY_TIMER_STARTED__" as const;
  
    if ((window as any)[key]) {
      console.log("Timer '[FinishedGoodSearch] page ready' already started, skip.");
      return;
    }
  
    (window as any)[key] = true;
    console.time("[FinishedGoodSearch] page ready");
  }, []);
  
  const [releasedOrderCount, setReleasedOrderCount] = useState<number>(0);
  useEffect(() => {
    console.time("[FinishedGoodSearch] initial render");
    return () => {
      console.timeEnd("[FinishedGoodSearch] initial render");
    };
  }, []);
  const fetchReleasedOrderCount = useCallback(async () => {
    try {
      const releasedOrders = await fetchReleasedDoPickOrders();
      const validCount = releasedOrders.length;
      setReleasedOrderCount(validCount);
    } catch (error) {
      console.error("Error fetching released order count:", error);
      setReleasedOrderCount(0);
    }
  }, []);
  /*
  const loadSummaries = useCallback(async () => {
    setIsLoadingSummary(true);
    try {
      const [s2, s4] = await Promise.all([
        fetchStoreLaneSummary("2/F"),
        fetchStoreLaneSummary("4/F")
      ]);
      setSummary2F(s2);
      setSummary4F(s4);
    } catch (error) {
      console.error("Error loading summaries:", error);
    } finally {
      setIsLoadingSummary(false);
    }
  }, []);
  
  useEffect(() => {
    loadSummaries();
    // 每30秒刷新一次

  }, [loadSummaries]);
  */
  const handleDraft = useCallback(async () =>{
    try{
      if (fgPickOrdersData.length === 0) {
        console.error("No FG Pick order data available");
        Swal.fire({
          title: "",
          text: t("Please take one pick order before printing the draft."),
          icon: "info"
        })
        return;
    }
    if (!selectedPrinterForDraft) {
      Swal.fire({
        position: "bottom-end",
        icon: "warning",
        text: t("Please select a printer first"),
        showConfirmButton: false,
        timer: 1500
      });
      return;
    }
    const currentFgOrder = fgPickOrdersData[0];

    const printRequest = {
      printerId: selectedPrinterForDraft.id,
      printQty: 1,
      isDraft: true,
      numOfCarton: 0,
      doPickOrderId: currentFgOrder.doPickOrderId
    };

    console.log("Printing draft with request: ", printRequest);

    const response = await printDN(printRequest);

    console.log("Print Draft response: ", response);

    if(response.success){
      Swal.fire({
        position: "bottom-end",
        icon: "success",
        text: t("Printed Successfully."),
        showConfirmButton: false,
        timer: 1500
      });
    } else {
      console.error("Print failed: ", response.message);
      Swal.fire({
          title: "",
          text: t("Please take one pick order before printing the draft."),
          icon: "info"
      })
    } 
    } catch(error){
      console.error("error: ", error)
    }
  },[t, fgPickOrdersData, selectedPrinterForDraft]);

  const handleAllDraft = useCallback(async () =>{
    try {
      const releasedOrders =  await fetchReleasedDoPickOrders();
      console.log('fgPickOrdersData length:' + releasedOrders.length)
      if (!selectedPrinterForAllDraft) {
        Swal.fire({
          position: "bottom-end",
          icon: "warning",
          text: t("Please select a printer first"),
          showConfirmButton: false,
          timer: 1500
        });
        return;
      }
      if(releasedOrders.length === 0) {
        console.log("No released do_pick_order records found");
          Swal.fire({
          title: "",
          text: t("No released pick order records found."),
          icon: "info"
        })
        return;
      }
      console.log("Found released orders:", releasedOrders);

      const confirmResult = await Swal.fire({
        title: t("Batch Print"),
        text: t("Confirm print: (") + releasedOrders.length.toString() + t("piece(s))"),
        icon: "question",
        showCancelButton: true,
        confirmButtonText: t("Confirm"),
        cancelButtonText: t("Cancel"),
        confirmButtonColor: "#8dba00",
        cancelButtonColor: "#F04438"
      });

      if (!confirmResult.isConfirmed) {
        return;
      }

      Swal.fire({
      title: t("Printing..."),
      text: t("Please wait..."),
      allowOutsideClick: false,
      allowEscapeKey: false,
      didOpen: () => {
        Swal.showLoading();
      }
      });

      for (const order of releasedOrders) {
        const doPickOrderId = order.id

        console.log(`Processing order - DoPickOrder ID: ${doPickOrderId}, Ticket No: ${order.ticketNo}`);

        const printRequest = {
          printerId: selectedPrinterForAllDraft.id,
          printQty: 1,
          isDraft: true,
          numOfCarton: 0,
          doPickOrderId: doPickOrderId
        };

        console.log("Printing draft with request:", printRequest)

        const response = await printDN(printRequest);
        if(!response.success) {
          console.error(`Print failed for order ${order.ticketNo}:`, response.message);
        }
      }

      Swal.fire({
        position: "bottom-end",
        icon: "success",
        text: t("Printed Successfully."),
        showConfirmButton: false,
        timer: 1500
      });
    } catch(error){
      console.error("Error in handleAllDraft:",error);
    }

  },[t, fgPickOrdersData, selectedPrinterForAllDraft]);

  const handlePrintTruckRoutingSummary = useCallback(async () => {
    const { storeId, truckLanceCode, date } = truckRoutingFilters;
    if (!storeId || !truckLanceCode || !date) {
      Swal.fire({
        position: "bottom-end",
        icon: "warning",
        text: "請先選擇 2/F 或 4/F、車線和日期",
        showConfirmButton: false,
        timer: 1800,
      });
      return;
    }

    setIsPrintingRoutingSummary(true);
    try {
      if (!selectedPrinterForAllDraft) {
        Swal.fire({
          position: "bottom-end",
          icon: "warning",
          text: t("Please select a printer first"),
          showConfirmButton: false,
          timer: 1500
        });
        return;
      }

      const precheck = await fetchTruckRoutingSummaryPrecheck({
        storeId,
        truckLanceCode,
        date,
      });
      if (precheck.hasUnpickedOrders) {
        const confirmResult = await Swal.fire({
          title: "仍有未執拾的成品訂單",
          text: `此車線仍有 ${precheck.unpickedOrderCount} 張未執拾的成品訂單，是否仍要列印？`,
          icon: "warning",
          showCancelButton: true,
          confirmButtonText: "仍要列印",
          cancelButtonText: "取消",
          confirmButtonColor: "#8dba00",
          cancelButtonColor: "#F04438",
        });
        if (!confirmResult.isConfirmed) {
          return;
        }
      }

      const qs = new URLSearchParams({
        printerId: selectedPrinterForAllDraft.id.toString(),
        printQty: "1",
        storeId,
        truckLanceCode,
        date,
      }).toString();
      const url = `${NEXT_PUBLIC_API_URL}/truck-routing-summary/print-direct?${qs}`;
      const response = await clientAuthFetch(url, {
        method: "GET",
      });
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP ${response.status}: ${errorText}`);
      }
      logFeatureUsage(
        FEATURE_USAGE.TRUCK_ROUTING_SUMMARY,
        FEATURE_USAGE_ACTION.PRINT,
        `direct:${storeId}:${truckLanceCode}:${date}`,
      );
      Swal.fire({
        position: "bottom-end",
        icon: "success",
        text: t("Printed Successfully."),
        showConfirmButton: false,
        timer: 1500
      });
    } catch (error) {
      console.error("Failed to print Truck Routing Summary", error);
      Swal.fire({
        icon: "error",
        text: "列印送貨路線摘要失敗，請稍後再試。",
      });
    } finally {
      setIsPrintingRoutingSummary(false);
    }
  }, [truckRoutingFilters, selectedPrinterForAllDraft, t]);

  const isTruckRoutingTab = tabIndex === 6;
  const canPrintTruckRoutingSummary = Boolean(
    truckRoutingFilters.storeId &&
      truckRoutingFilters.truckLanceCode &&
      truckRoutingFilters.date &&
      !isPrintingRoutingSummary,
  );



  useEffect(() => {
    fetchReleasedOrderCount();
  }, [fetchReleasedOrderCount]);

  useEffect(() => {
    if (tabIndex === 6) {
      logFeatureUsage(FEATURE_USAGE.TRUCK_ROUTING_SUMMARY, FEATURE_USAGE_ACTION.PAGE_VIEW);
    }
  }, [tabIndex]);

  useEffect(() => {
    const onAssigned = () => {
      localStorage.removeItem('hideCompletedUntilNext');
      setHideCompletedUntilNext(false);
     // loadSummaries();
    };
    window.addEventListener('pickOrderAssigned', onAssigned);
    return () => window.removeEventListener('pickOrderAssigned', onAssigned);
  }, []);
  // ... existing code ...

  useEffect(() => {
    const handleCompletionStatusChange = (event: CustomEvent) => {
      const { allLotsCompleted, tabIndex: eventTabIndex } = event.detail;
      
      // ✅ 修复：根据标签页和事件来源决定是否更新打印按钮状态
      if (eventTabIndex === undefined || eventTabIndex === tabIndex) {
        setPrintButtonsEnabled(allLotsCompleted);
        console.log(`Print buttons enabled for tab ${tabIndex}:`, allLotsCompleted);
      }
    };

    window.addEventListener('pickOrderCompletionStatus', handleCompletionStatusChange as EventListener);
    
    return () => {
      window.removeEventListener('pickOrderCompletionStatus', handleCompletionStatusChange as EventListener);
    };
  }, [tabIndex]); // ✅ 添加 tabIndex 依赖

  // ✅ 新增：处理标签页切换时的打印按钮状态重置
  useEffect(() => {
    // 当切换到成品提貨記錄標籤時，重置打印按钮状态
    if (tabIndex === 2 || tabIndex === 4) {
      setPrintButtonsEnabled(false);
      console.log("Reset print buttons for Pick Execution Record tab");
    }
  }, [tabIndex]);
/*
// ... existing code ...
const handleAssignByLane = useCallback(async (
  storeId: string, 
  truckDepartureTime: string, 
  truckLanceCode: string
) => {
  if (!currentUserId) {
    console.error("Missing user id in session");
    return;
  }
  
  setIsAssigning(true);
  try {
    const res = await assignByLane(currentUserId, storeId, truckLanceCode, truckDepartureTime);
    
    if (res.code === "SUCCESS") {
      console.log("✅ Successfully assigned pick order from lane", truckLanceCode);
      window.dispatchEvent(new CustomEvent('pickOrderAssigned'));
      loadSummaries(); // 刷新按钮状态
    } else if (res.code === "USER_BUSY") {
      Swal.fire({
        icon: "warning",
        title: t("Warning"),
        text: t("You already have a pick order in progess. Please complete it first before taking next pick order."),
        confirmButtonText: t("Confirm"),
        confirmButtonColor: "#8dba00"
      });
      window.dispatchEvent(new CustomEvent('pickOrderAssigned'));
    } else if (res.code === "NO_ORDERS") {
      Swal.fire({
        icon: "info",
        title: t("Info"),
        text: t("No available pick order(s) for this lane."),
        confirmButtonText: t("Confirm"),
        confirmButtonColor: "#8dba00"
      });
    } else {
      console.log("ℹ️ Assignment result:", res.message);
    }
  } catch (error) {
    console.error("❌ Error assigning by lane:", error);
    Swal.fire({
      icon: "error",
      title: t("Error"),
      text: t("Error occurred during assignment."),
      confirmButtonText: t("Confirm"),
      confirmButtonColor: "#8dba00"
    });
  } finally {
    setIsAssigning(false);
  }
}, [currentUserId, t, loadSummaries]);
  // ✅ Manual assignment handler - uses the action function
*/
  const handleTabChange = useCallback<NonNullable<TabsProps["onChange"]>>(
    (_e, newValue) => {
      setTabIndex(newValue);
    },
    [],
  );

  const handleSwitchToDetailTab = useCallback(() => {
    setTabIndex(1);
  }, []);

  const handleSwtitchToRecordTab = useCallback(() =>{
    setTabIndex(2);
  }, []);
  
  const openCreateModal = useCallback(async () => {
    console.log("testing")
    const res = await fetchAllItemsInClient()
    console.log(res)
    setItems(res)
    setIsOpenCreateModal(true)
  }, [])

  const closeCreateModal = useCallback(() => {
    setIsOpenCreateModal(false)
  }, [])

  useEffect(() => {
    
    if (tabIndex === 3) {
      const loadItems = async () => {
        try {
          const itemsData = await fetchAllItemsInClient();
          console.log("PickOrderSearch loaded items:", itemsData.length);
          setItems(itemsData);
        } catch (error) {
          console.error("Error loading items in PickOrderSearch:", error);
        }
      };
      
      // 如果还没有数据，则加载
      if (items.length === 0) {
        loadItems();
      }
    }
  }, [tabIndex, items.length]);
  useEffect(() => {
    const handleCompletionStatusChange = (event: CustomEvent) => {
      const { allLotsCompleted } = event.detail;
      setPrintButtonsEnabled(allLotsCompleted);
      console.log("Print buttons enabled:", allLotsCompleted);
    };

    window.addEventListener('pickOrderCompletionStatus', handleCompletionStatusChange as EventListener);
    
    return () => {
      window.removeEventListener('pickOrderCompletionStatus', handleCompletionStatusChange as EventListener);
    };
  }, []);
/*
  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => {
      const baseCriteria: Criterion<SearchParamNames>[] = [
        { 
          label: tabIndex === 3 ? t("Item Code") : t("Code"), 
          paramName: "code", 
          type: "text" 
        },
        {
          label: t("Type"),
          paramName: "type",
          type: "autocomplete",
          options: tabIndex === 3 
            ?
              [
                { value: "Consumable", label: t("Consumable") },
                { value: "Material", label: t("Material") },
                { value: "Product", label: t("Product") }
              ]
            : 
              sortBy(
                uniqBy(
                  pickOrders.map((po) => ({
                    value: po.type,
                    label: t(upperCase(po.type)),
                  })),
                  "value",
                ),
                "label",
              ),
        },
      ];
  
      // Add Job Order search for Create Item tab (tabIndex === 3)
      if (tabIndex === 3) {
        baseCriteria.splice(1, 0, {
          label: t("Job Order"),
          paramName: "jobOrderCode" as any, // Type assertion for now
          type: "text",
        });
        
        baseCriteria.splice(2, 0, {
          label: t("Target Date"),
          paramName: "targetDate",
          type: "date",
        });
      } else {
        baseCriteria.splice(1, 0, {
          label: t("Target Date From"),
          label2: t("Target Date To"),
          paramName: "targetDate",
          type: "dateRange",
        });
      }
  
      // Add Items/Item Name criteria
      baseCriteria.push({
        label: tabIndex === 3 ? t("Item Name") : t("Items"),
        paramName: "items",
        type: tabIndex === 3 ? "text" : "autocomplete", 
        options: tabIndex === 3 
          ? [] 
          : 
            uniqBy(
              flatten(
                sortBy(
                  pickOrders.map((po) =>
                    po.items
                      ? po.items.map((item) => ({
                          value: item.name,
                          label: item.name,
                        }))
                      : [],
                  ),
                  "label",
                ),
              ),
              "value",
            ),
      });
  
      // Add Status criteria for non-Create Item tabs
      if (tabIndex !== 3) {
        baseCriteria.push({
          label: t("Status"),
          paramName: "status",
          type: "autocomplete",
          options: sortBy(
            uniqBy(
              pickOrders.map((po) => ({
                value: po.status,
                label: t(po.status),
              })),
              "value",
            ),
            "label",
          ),
        });
      }
  
      return baseCriteria;
    },
    [pickOrders, t, tabIndex, items],
  );
*/
/*
    const fetchNewPagePickOrder = useCallback(
      async (
        pagingController: Record<string, number>,
        filterArgs: Record<string, number>,
      ) => {
        const params = {
          ...pagingController,
          ...filterArgs,
        };
        const res = await fetchPickOrderClient(params);
        if (res) {
          console.log(res);
          setFilteredPickOrders(res.records);
          setTotalCount(res.total);
        }
      },
      [],
    );
    */
/*
  const onReset = useCallback(() => {
    setFilteredPickOrders(pickOrders);
  }, [pickOrders]);
*/
  useEffect(() => {
    if (!isOpenCreateModal) {
      setTabIndex(1)
      setTimeout(async () => {
      setTabIndex(0)
      }, 200)
    }
  }, [isOpenCreateModal])
  
  // 添加处理提料单创建成功的函数
  const handlePickOrderCreated = useCallback(() => {
    // 切换到 Assign & Release 标签页 (tabIndex = 1)
    setTabIndex(2);
  }, []);

  return (
    <Box sx={{ 
 // Full viewport height
      overflow: 'auto' // Single scrollbar for the whole page
    }}>
    
    
      {/* Header section */}
      <Box
        sx={{
          p: 1,
          borderBottom: '1px solid #e0e0e0',
          minHeight: 'auto',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between', // 左标题，右控件
          gap: 2,
          flexWrap: 'wrap',                // 如果屏幕窄就自动换行
        }}
      >
        {/* 左侧标题 */}
        <Typography
          variant="h5"
          sx={{
            lineHeight: 1.4,
            m: 0,
            fontWeight: 500,
          }}
        >
          {t("Finished Good Order")}
        </Typography>

        {/* 右侧：打印机 + 按钮 */}
        <Stack
          direction="row"
          spacing={2}
          sx={{
            alignItems: 'center',
            flexWrap: 'wrap',   // 控件太多时换行，不会撑出横向滚动
            rowGap: 1,
          }}
        >
          <Typography variant="body2" sx={{ minWidth: 'fit-content', mr: 1.5 }}>
            {t("A4 Printer")}:
          </Typography>
          <Autocomplete
            options={(printerCombo || []).filter(printer => printer.type === 'A4')}
            getOptionLabel={(option) =>
              option.name || option.label || option.code || `Printer ${option.id}`
            }
            value={selectedPrinterForAllDraft}
            onChange={(_, newValue) => setSelectedPrinterForAllDraft(newValue)}
            sx={{ minWidth: 200 }}
            size="small"
            renderInput={(params) => (
              <TextField {...params} placeholder={t("A4 Printer")}inputProps={{ ...params.inputProps, readOnly: true }} />
            )}
          />

          <Typography variant="body2" sx={{ minWidth: 'fit-content', ml: 1 }}>
            {t("Label Printer")}:
          </Typography>
          <Autocomplete
            options={(printerCombo || []).filter(printer => printer.type === 'Label')}
            getOptionLabel={(option) =>
              option.name || option.label || option.code || `Printer ${option.id}`
            }
            value={selectedPrinterForDraft}
            onChange={(_, newValue) => setSelectedPrinterForDraft(newValue)}
            sx={{ minWidth: 200 }}
            size="small"
            renderInput={(params) => (
              <TextField {...params} placeholder={t("Label Printer")} inputProps={{ ...params.inputProps, readOnly: true }}/>
            )}
          />

          <Button
            variant="contained"
            sx={{
              py: 0.5,
              px: 1.25,
              height: '40px',
              fontSize: '0.75rem',
              lineHeight: 1.2,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              '&.Mui-disabled': {
                height: '40px',
              },
            }}
            onClick={isTruckRoutingTab ? handlePrintTruckRoutingSummary : handleAllDraft}
            disabled={isTruckRoutingTab ? !canPrintTruckRoutingSummary : false}
          >
            {isTruckRoutingTab
              ? isPrintingRoutingSummary
                ? "生成中..."
                : "列印報告"
              : `${t("Print All Draft")} (${releasedOrderCount})`}
          </Button>
{/*
          <Button
            variant="contained"
            sx={{
              py: 0.5,
              px: 1.25,
              height: '40px',
              fontSize: '0.75rem',
              lineHeight: 1.2,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              '&.Mui-disabled': {
                height: '40px',
              },
            }}
            title={!printButtonsEnabled ? t("All lots must be completed before printing") : ""}
            onClick={handleDraft}
          >
            {t("Print Draft")}
          </Button>
          */}
        </Stack>
      </Box>


      {/* Tabs section - ✅ Move the click handler here */}
      <Box sx={{ 
        borderBottom: '1px solid #e0e0e0'
      }}>
        <Tabs value={tabIndex} onChange={handleTabChange} variant="scrollable">
        <Tab label={t("Pick Order Detail")} iconPosition="end"  />
        <Tab label={t("Finished Good Detail")} iconPosition="end"  />
        <Tab label={t("Finished Good Record")} iconPosition="end"  />
        <Tab label={t("Ticket Release Table")} iconPosition="end"  />
        <Tab label={t("Finished Good Record (All)")} iconPosition="end"  />
        <Tab label="成品出倉出箱數量" iconPosition="end" />
        <Tab label="送貨路線摘要" iconPosition="end" />
        </Tabs>
  
      </Box>

      {/* Content section - NO overflow: 'auto' here */}
      <Box sx={{ p: 2 }}>

        {tabIndex === 0 && (
          <PickExecution 
            filterArgs={filterArgs} 
            onFgPickOrdersChange={setFgPickOrdersData}
            onSwitchToDetailTab={handleSwitchToDetailTab}
            onFirstLoadDone={() => {
              if (typeof window === "undefined") return;
              const key = "__FG_PAGE_READY_TIMER_STARTED__" as const;
          
              // 只在计时器真的存在时才调用 timeEnd，避免 "does not exist"
              if ((window as any)[key]) {
                console.timeEnd("[FinishedGoodSearch] page ready");
                delete (window as any)[key];
              } else {
                console.log("Timer '[FinishedGoodSearch] page ready' was already ended, skip.");
              }
            }}
          />
        )}
        {/*
        {tabIndex === 1 && (
          /*<PickExecutionDetail 
            filterArgs={filterArgs}
            onSwitchToRecordTab={handleSwtitchToRecordTab}
            onRefreshReleasedOrderCount={fetchReleasedOrderCount}
          />
        ) */}
        {tabIndex === 2 && (
          <GoodPickExecutionRecord
            filterArgs={filterArgs}
            printerCombo={printerCombo}
            a4Printer={selectedPrinterForAllDraft}
            labelPrinter={selectedPrinterForDraft}
            recordTabIndex={2}
            listScope="mine"
          />
        )}
        {tabIndex === 3 && <FGPickOrderTicketReleaseTable />}
        {tabIndex === 4 && (
          <GoodPickExecutionRecord
            filterArgs={filterArgs}
            printerCombo={printerCombo}
            a4Printer={selectedPrinterForAllDraft}
            labelPrinter={selectedPrinterForDraft}
            recordTabIndex={4}
            listScope="all"
          />
        )}
        {tabIndex === 5 && (
          <FinishedGoodCartonDashboardTab />
        )}
        {tabIndex === 6 && (
          <TruckRoutingSummaryTab onFiltersChange={setTruckRoutingFilters} />
        )}
      </Box>
    </Box>
  );
};

export default PickOrderSearch;