"use client";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Grid, Stack, Tab, Tabs, TabsProps, Typography, Box } from "@mui/material";
import WorkbenchPickExecution from "./WorkbenchPickExecution";
import PickExecution from "./PickExecution";
import NewCreateItem from "./newcreatitem";
import AssignAndRelease from "./AssignAndRelease";
import AssignTo from "./assignTo";
import { fetchAllItemsInClient, ItemCombo } from "@/app/api/settings/item/actions";

interface Props {
  // Intentionally empty: data is loaded per-tab now.
}

const PickOrderSearch: React.FC<Props> = () => {
  const { t } = useTranslation("pickOrder");

  const [isOpenCreateModal, setIsOpenCreateModal] = useState(false);
  const [items, setItems] = useState<ItemCombo[]>([]);
  const [filterArgs, setFilterArgs] = useState<Record<string, any>>({});
  const [searchQuery, setSearchQuery] = useState<Record<string, any>>({}); 
  const [tabIndex, setTabIndex] = useState(0);

  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(() => {
    if (!isOpenCreateModal) {
      setTabIndex(1);
      setTimeout(async () => {
        setTabIndex(0);
      }, 200);
    }
  }, [isOpenCreateModal]);
  
  // 添加处理提料单创建成功的函数
  const handlePickOrderCreated = useCallback(() => {
    // 切换到 Assign & Release 标签页 (tabIndex = 1)
    setTabIndex(1);
  }, []);

  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>
            <Grid item xs={8}>
              <Typography variant="h4" marginInlineEnd={2}>
                {t("Pick Order")}
              </Typography>
            </Grid>
            {/*
            <Grid item xs={4} display="flex" justifyContent="end" alignItems="end">
              <Button onClick={openCreateModal}>
                {t("create")}
              </Button>
              {isOpenCreateModal && 
                <CreatePickOrderModal 
                  open={isOpenCreateModal} 
                  onClose={closeCreateModal}
                  items={items}
                />
              }
            </Grid>
            */}
          </Grid>
        </Stack>
      </Box>

      {/* Tabs section */}
      <Box sx={{ 
        borderBottom: '1px solid #e0e0e0'
      }}>
        <Tabs value={tabIndex} onChange={handleTabChange} variant="scrollable">
          <Tab label={t("Select Items")} iconPosition="end" />
          {/* <Tab label={t("Select Job Order Items")} iconPosition="end" /> */}
          <Tab label={t("Assign")} iconPosition="end" />
         {/* <Tab label={t("Release")} iconPosition="end" /> */}
          {/* <Tab label={t("Pick Execution")} iconPosition="end" /> */}
          <Tab label={t("Pick Execution")} iconPosition="end" />
          {/* <Tab label={t("old Pick Execution")} iconPosition="end" /> */}
        </Tabs>
      </Box>

      {/* Content section - NO overflow: 'auto' here */}
      <Box sx={{ 
        p: 2
      }}>
       {tabIndex === 2 && <WorkbenchPickExecution filterArgs={filterArgs} />}
       {/* {tabIndex === 3 && <PickExecution filterArgs={filterArgs} />}  */}
        {tabIndex === 0 && (
          <NewCreateItem 
            filterArgs={filterArgs} 
            searchQuery={searchQuery} 
            onPickOrderCreated={handlePickOrderCreated}
          />
        )}
       {/* {tabIndex === 1 && <Jobcreatitem filterArgs={filterArgs} />} */}
        {tabIndex === 1 && <AssignAndRelease filterArgs={filterArgs} />}
        {/* {tabIndex === 2 && <AssignTo filterArgs={filterArgs} />} */}
      </Box>
    </Box>
  );
};

export default PickOrderSearch;
