"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,
  upperFirst,
} from "lodash";
import {
  arrayToDayjs,
} from "@/app/utils/formatUtil";
import JoPickOrderList from "@/components/JoWorkbench/JoPickOrderList";
import { Button, Grid, Stack, Tab, Tabs, TabsProps, Typography, Box, TextField, Autocomplete } from "@mui/material";
import Jodetail from "./Jodetail"
import PickExecution from "./JobPickExecution";
import { fetchAllItemsInClient, ItemCombo } from "@/app/api/settings/item/actions";
import { fetchPickOrderClient, autoAssignAndReleasePickOrder, autoAssignAndReleasePickOrderByStore } from "@/app/api/pickOrder/actions";
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig";
import JobPickExecutionsecondscan from "./JobPickExecutionsecondscan";
import FInishedJobOrderRecord from "./FInishedJobOrderRecord";
import JobPickExecution from "./JobPickExecution";
import CompleteJobOrderRecord from "./completeJobOrderRecord";
//import JoPickOrderList from "./JoPickOrderList";
import { 
 // fetchUnassignedJobOrderPickOrders, 
  assignJobOrderPickOrder,
  fetchJobOrderLotsHierarchical,
  fetchCompletedJobOrderPickOrders,
  fetchCompletedJobOrderPickOrderRecords
} from "@/app/api/jo/actions";
import { fetchPrinterCombo } from "@/app/api/settings/printer";
import { PrinterCombo } from "@/app/api/settings/printer";
import JoPickOrderDetail from "./JoPickOrderDetail";
import MaterialPickStatusTable from "./MaterialPickStatusTable";
import PlasticBoxCartonDashboardTab from "./PlasticBoxCartonDashboardTab";
interface Props {
  //pickOrders: PickOrderResult[];
  printerCombo: PrinterCombo[];
}

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

type SearchParamNames = keyof SearchQuery;

const JodetailSearch: React.FC<Props> = ({ printerCombo }) => {
  const { t } = useTranslation("jo");
  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 [unassignedOrders, setUnassignedOrders] = useState<any[]>([]);
  const [isLoadingUnassigned, setIsLoadingUnassigned] = useState(false);
  const [hasAssignedJobOrders, setHasAssignedJobOrders] = useState(false);
  const [hasDataTab0, setHasDataTab0] = useState(false);
  const [hasDataTab1, setHasDataTab1] = useState(false);
  const hasAnyAssignedData = hasDataTab0 || hasDataTab1;
  
  // Add printer selection state
  const [selectedPrinter, setSelectedPrinter] = useState<PrinterCombo | null>(
    printerCombo && printerCombo.length > 0 ? printerCombo[0] : null
  );
  const [printQty, setPrintQty] = useState<number>(1);
  
  const [hideCompletedUntilNext, setHideCompletedUntilNext] = useState<boolean>(
    typeof window !== 'undefined' && localStorage.getItem('hideCompletedUntilNext') === 'true'
  );
  useEffect(() => {
    const onJobOrderDataStatus = (e: CustomEvent) => {
      const { hasData, tabIndex: idx } = e.detail || {};
      if (idx === 0) setHasDataTab0(!!hasData);
      if (idx === 1) setHasDataTab1(!!hasData);
    };
    window.addEventListener('jobOrderDataStatus', onJobOrderDataStatus as EventListener);
    return () => window.removeEventListener('jobOrderDataStatus', onJobOrderDataStatus as EventListener);
  }, []);
  useEffect(() => {
    const handleJobOrderDataChange = (event: CustomEvent) => {
      const { hasData, tabIndex: eventTabIndex } = event.detail;
      
      // Update the state based on which tab has data
      if (eventTabIndex === 0 || eventTabIndex === 1) {
        setHasAssignedJobOrders(hasData);
        console.log(`Job order data status for tab ${eventTabIndex}:`, hasData);
      }
    };

    window.addEventListener('jobOrderDataStatus', handleJobOrderDataChange as EventListener);
    
    return () => {
      window.removeEventListener('jobOrderDataStatus', handleJobOrderDataChange as EventListener);
    };
  }, []);
  
  useEffect(() => {
    const onAssigned = () => {
      localStorage.removeItem('hideCompletedUntilNext');
      setHideCompletedUntilNext(false);
    };
    window.addEventListener('pickOrderAssigned', onAssigned);
    return () => window.removeEventListener('pickOrderAssigned', onAssigned);
  }, []);

  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]);

  //  新增：处理标签页切换时的打印按钮状态重置
  useEffect(() => {
    // 当切换到标签页 2 (GoodPickExecutionRecord) 时，重置打印按钮状态
    if (tabIndex === 2) {
      setPrintButtonsEnabled(false);
      console.log("Reset print buttons for Pick Execution Record tab");
    }
  }, [tabIndex]);

  const handleAssignByStore = async (storeId: "2/F" | "4/F") => {
    if (!currentUserId) {
      console.error("Missing user id in session");
      return;
    }
    
    setIsAssigning(true);
    try {
      const res = await autoAssignAndReleasePickOrderByStore(currentUserId, storeId);
      console.log("Assign by store result:", res);
      
      //  Handle different response codes
      if (res.code === "SUCCESS") {
        console.log(" Successfully assigned pick order to store", storeId);
        //  Trigger refresh to show newly assigned data
        window.dispatchEvent(new CustomEvent('pickOrderAssigned'));
      } else if (res.code === "USER_BUSY") {
        console.warn("⚠️ User already has pick orders in progress:", res.message);
        //  Show warning but still refresh to show existing orders
        alert(`Warning: ${res.message}`);
        window.dispatchEvent(new CustomEvent('pickOrderAssigned'));
      } else if (res.code === "NO_ORDERS") {
        console.log("ℹ️ No available pick orders for store", storeId);
        alert(`Info: ${res.message}`);
      } else {
        console.log("ℹ️ Assignment result:", res.message);
        alert(`Info: ${res.message}`);
      }
    } catch (error) {
      console.error("❌ Error assigning by store:", error);
      alert("Error occurred during assignment");
    } finally {
      setIsAssigning(false);
    }
  };
  //  Manual assignment handler - uses the action function
  /*
  const loadUnassignedOrders = useCallback(async () => {
    setIsLoadingUnassigned(true);
    try {
      const orders = await fetchUnassignedJobOrderPickOrders();
      setUnassignedOrders(orders);
    } catch (error) {
      console.error("Error loading unassigned orders:", error);
      setUnassignedOrders([]);
    } finally {
      setIsLoadingUnassigned(false);
    }
  }, []);
  */
  // 分配订单给当前用户
  const handleAssignOrder = useCallback(async (pickOrderId: number) => {
    if (!currentUserId) {
      console.error("Missing user id in session");
      return;
    }
    
    try {
      const result = await assignJobOrderPickOrder(pickOrderId, currentUserId);
      if (result.message === "Successfully assigned") {
        console.log(" Successfully assigned pick order");
        // 刷新数据
        window.dispatchEvent(new CustomEvent('pickOrderAssigned'));
        // 重新加载未分配订单列表
       // loadUnassignedOrders();
      } else {
        console.warn("⚠️ Assignment failed:", result.message);
        alert(`Assignment failed: ${result.message}`);
      }
    } catch (error) {
      console.error("❌ Error assigning order:", error);
      alert("Error occurred during assignment");
    }
  }, [currentUserId]);
  
  // 在组件加载时获取未分配订单
  /*
  useEffect(() => {
    if (tabIndex === 0) {
      loadUnassignedOrders();
    }
  }, [tabIndex, loadUnassignedOrders]);
  */
  const handleTabChange = useCallback<NonNullable<TabsProps["onChange"]>>(
    (_e, newValue) => {
      setTabIndex(newValue);
    },
    [],
  );
  
  const openCreateModal = useCallback(async () => {
    console.log("testing")
    const res = await fetchAllItemsInClient()
    console.log(res)
    setItems(res)
    setIsOpenCreateModal(true)
  }, [])

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

  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(upperFirst(po.status)),
              })),
              "value",
            ),
            "label",
          ),
        });
      }
  
      return baseCriteria;
    },
    [pickOrders, t, tabIndex, items],
  );
  */
  const handleSwitchToRecordTab = useCallback(() => {
    setTabIndex(1); // 切换到 CompleteJobOrderRecord 标签页（tabIndex 1）
  }, []);
/*
    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={{ 
      height: '100vh',
      overflow: 'auto'
    }}>
      {/* Header section with printer selection */}
      <Box sx={{ 
        p: 1,
        borderBottom: '1px solid #e0e0e0',
        minHeight: 'auto',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        gap: 2,
        flexWrap: 'wrap',
      }}>
        {/* Left side - Title */}

        {/* Right side - Printer selection (only show on tab 1) */}
        {tabIndex === 1 && (
          <Stack
            direction="row"
            spacing={2}
            sx={{
              alignItems: 'center',
              flexWrap: 'wrap',
              rowGap: 1,
            }}
          >
            <Typography variant="body2" sx={{ minWidth: 'fit-content', mr: 1.5 }}>
              {t("Select Printer")}:
            </Typography>
            <Autocomplete
              options={(printerCombo || []).filter(printer => printer.type === 'A4')}
              getOptionLabel={(option) =>
                option.name || option.label || option.code || `Printer ${option.id}`
              }
              value={selectedPrinter}
              onChange={(_, newValue) => setSelectedPrinter(newValue)}
              sx={{ minWidth: 200 }}
              size="small"
              renderInput={(params) => (
                <TextField {...params} placeholder={t("Printer")}inputProps={{ ...params.inputProps, readOnly: true }} />
              )}
            />
            <Typography variant="body2" sx={{ minWidth: 'fit-content', ml: 1 }}>
              {t("Print Quantity")}:
            </Typography>
            <TextField
              type="number"
              label={t("Print Quantity")}
              value={printQty}
              onChange={(e) => {
                const value = parseInt(e.target.value) || 1;
                setPrintQty(Math.max(1, value));
              }}
              inputProps={{ min: 1, step: 1 }}
              sx={{ width: 120 }}
              size="small"
            />
          </Stack>
        )}
      </Box>

      {/* Tabs section */}
      <Box sx={{ 
        borderBottom: '1px solid #e0e0e0'
      }}>
        <Tabs value={tabIndex} onChange={handleTabChange} variant="scrollable">
          <Tab label={t("Jo Pick Order Detail")} iconPosition="end"  />
          <Tab label={t("Complete Job Order Record")} iconPosition="end"  />
          <Tab label={t("Material Pick Status")} iconPosition="end"  />
          <Tab label={t("Plastic box carton qty dashboard")} iconPosition="end"  />
        </Tabs>
      </Box>

      {/* Content section */}
      <Box sx={{ p: 2 }}>
        {tabIndex === 0 && <JoPickOrderList onSwitchToRecordTab={handleSwitchToRecordTab} printerCombo={printerCombo} />}
        {tabIndex === 1 && (
          <CompleteJobOrderRecord 
            filterArgs={filterArgs} 
            printerCombo={printerCombo}
            selectedPrinter={selectedPrinter}
            printQty={printQty}
          />
        )}
        {tabIndex === 2 && <MaterialPickStatusTable />}
        {tabIndex === 3 && <PlasticBoxCartonDashboardTab />}
      </Box>
    </Box>
  );
};

export default JodetailSearch;