"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 { Button, Grid, Stack, Tab, Tabs, TabsProps, Typography, Box } 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 } from "@/app/api/pickOrder/actions";
import FGPickOrderCard from "./FGPickOrderCard";

interface Props {
  pickOrders: PickOrderResult[];
}

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

type SearchParamNames = keyof SearchQuery;

const PickOrderSearch: React.FC<Props> = ({ pickOrders }) => {
  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 [hideCompletedUntilNext, setHideCompletedUntilNext] = useState<boolean>(
    typeof window !== 'undefined' && localStorage.getItem('hideCompletedUntilNext') === 'true'
  );

  const [fgPickOrdersData, setFgPickOrdersData] = useState<FGPickOrderResponse[]>([]);
  const [releasedOrderCount, setReleasedOrderCount] = useState<number>(0);

  const fetchReleasedOrderCount = useCallback(async () => {
    try {
      const releasedOrders = await fetchReleasedDoPickOrders();
      // Count only orders that have a valid doOrderId
      const validCount = releasedOrders.filter(order => order.doOrderId).length;
      setReleasedOrderCount(validCount);
    } catch (error) {
      console.error("Error fetching released order count:", error);
      setReleasedOrderCount(0);
    }
  }, []);

  const handleDraft = useCallback(async () =>{
    try{
      if (fgPickOrdersData.length === 0) {
        console.error("No FG Pick order data available");
        return;
    }

    const currentFgOrder = fgPickOrdersData[0];

    const printRequest = {
      printerId: 1,
      printQty: 1,
      isDraft: true,
      numOfCarton: 0,
      deliveryOrderId: currentFgOrder.deliveryOrderId,
      pickOrderId: currentFgOrder.pickOrderId
    };

    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: "info",
        text: t("Printed Successfully."),
        showConfirmButton: false,
        timer: 1500
      });
    } else {
      console.error("Print failed: ", response.message);
    } 
    } catch(error){
      console.error("error: ", error)
    }
  },[t, fgPickOrdersData]);

  const handleAllDraft = useCallback(async () =>{
    try {
      const releasedOrders = await fetchReleasedDoPickOrders();

      if(releasedOrders.length === 0) {
        console.log("No released do_pick_order records found");
        
        return;
      }
      console.log("Found released orders:", releasedOrders);

      const confirmResult = await Swal.fire({
        title: t("Confirm Print"),
        text: t(`Do you want to print ${releasedOrders.length} draft(s)?`),
        icon: "question",
        showCancelButton: true,
        confirmButtonText: t("Yes, print"),
        cancelButtonText: t("Cancel"),
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33"
      });

      // If user cancels, exit the function
      if (!confirmResult.isConfirmed) {
        return;
      }

      for (const order of releasedOrders) {
        const { doOrderId, pickOrderId } = order;

        console.log(`Processing order - DO Order ID: ${doOrderId}, Pick order ID: ${pickOrderId}`);

        const printRequest = {
          printerId: 1,
          printQty: 1,
          isDraft: true,
          numOfCarton: 0,
          deliveryOrderId: doOrderId,
          pickOrderId: pickOrderId
        };

        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 ${releasedOrders.length} draft(s) successfully.`),
        showConfirmButton: false,
        timer: 1500
      });
    } catch(error){
      console.error("Error in handleAllDraft:",error);
    }

  },[t]);

  const handleDN = useCallback(async () =>{
    const askNumofCarton = await Swal.fire({
      title: t("Enter the number of cartons: "),
      input: "number",
      inputPlaceholder: t("Number of cartons"),
      inputAttributes:{
        min: "1",
        step: "1"
      },
      inputValidator: (value) => {
        if(!value){
          return t("You need to enter a number")
        }
        if(parseInt(value) < 1){
          return t("Number must be at least 1");
        }
        return null
      },
      showCancelButton: true,
      confirmButtonText: t("Confirm"),
      cancelButtonText: t("Cancel"),
      showLoaderOnConfirm: true,
      allowOutsideClick: () => !Swal.isLoading()
    });

    if (askNumofCarton.isConfirmed) {
      const numOfCartons = askNumofCarton.value;
      try{
        if (fgPickOrdersData.length === 0) {
        console.error("No FG Pick order data available");
        return;
      }

      const currentFgOrder = fgPickOrdersData[0];

      const printRequest = {
        printerId: 1,
        printQty: 1,
        isDraft: false,
        numOfCarton: numOfCartons,
        deliveryOrderId: currentFgOrder.deliveryOrderId,
        pickOrderId: currentFgOrder.pickOrderId
      };

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

      const response = await printDN(printRequest);

      console.log("Print Delivery Note response: ", response);

      if(response.success){
        Swal.fire({
          position: "bottom-end",
          icon: "info",
          text: t("Printed Successfully."),
          showConfirmButton: false,
          timer: 1500
        });
      } else {
        console.error("Print failed: ", response.message);
      } 
      } catch(error){
        console.error("error: ", error)
      }
    }
  },[t, fgPickOrdersData]);

  const handleDNandLabel = useCallback(async () =>{
    const askNumofCarton = await Swal.fire({
      title: t("Enter the number of cartons: "),
      input: "number",
      inputPlaceholder: t("Number of cartons"),
      inputAttributes:{
        min: "1",
        step: "1"
      },
      inputValidator: (value) => {
        if(!value){
          return t("You need to enter a number")
        }
        if(parseInt(value) < 1){
          return t("Number must be at least 1");
        }
        return null
      },
      showCancelButton: true,
      confirmButtonText: t("Confirm"),
      cancelButtonText: t("Cancel"),
      showLoaderOnConfirm: true,
      allowOutsideClick: () => !Swal.isLoading()
    });

    if (askNumofCarton.isConfirmed) {
      const numOfCartons = askNumofCarton.value;
      try{
        if (fgPickOrdersData.length === 0) {
        console.error("No FG Pick order data available");
        return;
      }

      const currentFgOrder = fgPickOrdersData[0];

      const printDNRequest = {
        printerId: 1,
        printQty: 1,
        isDraft: false,
        numOfCarton: numOfCartons,
        deliveryOrderId: currentFgOrder.deliveryOrderId,
        pickOrderId: currentFgOrder.pickOrderId
      };

      const printDNLabelsRequest = {
        printerId: 1,
        printQty: 1,
        numOfCarton: numOfCartons,
        deliveryOrderId: currentFgOrder.deliveryOrderId
      };
      
      console.log("Printing Labels with request: ", printDNLabelsRequest);
      console.log("Printing DN with request: ", printDNRequest);

      const LabelsResponse = await printDNLabels(printDNLabelsRequest);
      const DNResponse = await printDN(printDNRequest);
      
      console.log("Print Labels response: ", LabelsResponse);
      console.log("Print DN response: ", DNResponse);

      if(LabelsResponse.success && DNResponse.success){
        Swal.fire({
          position: "bottom-end",
          icon: "info",
          text: t("Printed Successfully."),
          showConfirmButton: false,
          timer: 1500
        });
      } else {
        if(!LabelsResponse.success){
          console.error("Print failed: ", LabelsResponse.message);
        }
        else{
          console.error("Print failed: ", DNResponse.message);
        }
      } 
      } catch(error){
        console.error("error: ", error)
      }
    }
  },[t, fgPickOrdersData]);

  const handleLabel = useCallback(async () =>{
    const askNumofCarton = await Swal.fire({
      title: t("Enter the number of cartons: "),
      input: "number",
      inputPlaceholder: t("Number of cartons"),
      inputAttributes:{
        min: "1",
        step: "1"
      },
      inputValidator: (value) => {
        if(!value){
          return t("You need to enter a number")
        }
        if(parseInt(value) < 1){
          return t("Number must be at least 1");
        }
        return null
      },
      showCancelButton: true,
      confirmButtonText: t("Confirm"),
      cancelButtonText: t("Cancel"),
      showLoaderOnConfirm: true,
      allowOutsideClick: () => !Swal.isLoading()
    });

    if (askNumofCarton.isConfirmed) {
      const numOfCartons = askNumofCarton.value;
      try{
        if (fgPickOrdersData.length === 0) {
          console.error("No FG Pick order data available");
          return;
        }
      
        const currentFgOrder = fgPickOrdersData[0];

        const printRequest = {
          printerId: 1,
          printQty: 1,
          numOfCarton: numOfCartons,
          deliveryOrderId: currentFgOrder.deliveryOrderId,
        };

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

        const response = await printDNLabels(printRequest);

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

        if(response.success){
          Swal.fire({
            position: "bottom-end",
            icon: "info",
            text: t("Printed Successfully."),
            showConfirmButton: false,
            timer: 1500
          });
        } else {
          console.error("Print failed: ", response.message);
        } 
        } catch(error){
          console.error("error: ", error)
        }
    }
  },[t, fgPickOrdersData]);

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

  useEffect(() => {
    const onAssigned = () => {
      localStorage.removeItem('hideCompletedUntilNext');
      setHideCompletedUntilNext(false);
    };
    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(() => {
    // 当切换到标签页 2 (GoodPickExecutionRecord) 时，重置打印按钮状态
    if (tabIndex === 2) {
      setPrintButtonsEnabled(false);
      console.log("Reset print buttons for Pick Execution Record tab");
    }
  }, [tabIndex]);

// ... existing code ...
  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 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(() => {
    
    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(upperFirst(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={{ 
      height: '100vh', // Full viewport height
      overflow: 'auto' // Single scrollbar for the whole page
    }}>
      {/* Header section */}
      <Box sx={{ p: 2, borderBottom: '1px solid #e0e0e0' }}>
  <Stack rowGap={2}>
    <Grid container alignItems="center">
    <Grid item xs={8}>
  <Box mb={2}>
    <Typography variant="h4" marginInlineEnd={2}>
      {t("Finished Good Order")}
    </Typography>
  </Box>
</Grid>

      {/* Last 2 buttons aligned right */}
      <Grid item xs={6} >
        <Stack direction="row" spacing={1}>
          <Button
            variant="contained"
            onClick={() => handleAssignByStore("2/F")}
            disabled={isAssigning}
          >
            {isAssigning ? t("Assigning pick order...") : t("Pick Execution 2/F")}
          </Button>
          <Button
            variant="contained"
            onClick={() => handleAssignByStore("4/F")}
            disabled={isAssigning}
          >
            {isAssigning ? t("Assigning pick order...") : t("Pick Execution 4/F")}
          </Button>
        </Stack>
      </Grid>
      {/* ✅ Updated print buttons with completion status */}
      <Grid item xs={6} display="flex" justifyContent="flex-end">
              <Stack direction="row" spacing={1}>
                <Button
                  variant="contained"
                  onClick={handleAllDraft}
                >
                  {t("Print All Draft")} ({releasedOrderCount})
                </Button>

                <Button 
                  variant="contained"
                 // disabled={!printButtonsEnabled}
                  title={!printButtonsEnabled ? t("All lots must be completed before printing") : ""}
                  onClick={handleDraft}
                >
                  {t("Print Draft")}
                </Button>
                <Button 
                  variant="contained"
                 disabled={!printButtonsEnabled}
                  title={!printButtonsEnabled ? t("All lots must be completed before printing") : ""}
                  onClick={handleDNandLabel}
                >
                  {t("Print Pick Order and DN Label")}
                </Button>
                <Button 
                  variant="contained"
                 disabled={!printButtonsEnabled}
                  title={!printButtonsEnabled ? t("All lots must be completed before printing") : ""}
                  onClick={handleDN}
                >
                  {t("Print Pick Order")}
                </Button>
                <Button 
                  variant="contained"
                 disabled={!printButtonsEnabled}
                  title={!printButtonsEnabled ? t("All lots must be completed before printing") : ""}
                  onClick={handleLabel}
                >
                  {t("Print DN Label")}
                </Button>
              </Stack>
            </Grid>


    </Grid>
  </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"  />
        </Tabs>
  
      </Box>

      {/* Content section - NO overflow: 'auto' here */}
      <Box sx={{ 
        p: 2
      }}>
        {tabIndex === 0 && <PickExecution filterArgs={filterArgs} onFgPickOrdersChange={setFgPickOrdersData}/>}
        {tabIndex === 1 && <PickExecutionDetail filterArgs={filterArgs} />}
        {tabIndex === 2 && <GoodPickExecutionRecord filterArgs={filterArgs} />}
      </Box>
    </Box>
  );
};

export default PickOrderSearch;