"use client";
import React, { useState, useEffect, useCallback } from "react";
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig";
import { Box, Tabs, Tab, Stack, Typography, Autocomplete, TextField } from "@mui/material";
import ProductionProcessList from "@/components/ProductionProcess/ProductionProcessList";
import ProductionProcessDetail from "@/components/ProductionProcess/ProductionProcessDetail";
import ProductionProcessJobOrderDetail from "@/components/ProductionProcess/ProductionProcessJobOrderDetail";
import JobPickExecutionsecondscan from "@/components/Jodetail/JobPickExecutionsecondscan";
import FinishedQcJobOrderList from "@/components/ProductionProcess/FinishedQcJobOrderList";
import { 
  fetchProductProcesses, 
  fetchProductProcessesByJobOrderId,
  ProductProcessLineResponse 
} from "@/app/api/jo/actions";
import { useTranslation } from "react-i18next";

type PrinterCombo = {
  id: number;
  value: number;
  label?: string;
  code?: string;
  name?: string;
  description?: string;
  ip?: string;
  port?: number;
};

interface ProductionProcessPageProps {
  printerCombo: PrinterCombo[];
}

const STORAGE_KEY = 'productionProcess_selectedMatchingStock';

const ProductionProcessPage: React.FC<ProductionProcessPageProps> = ({ printerCombo }) => {
  const { t } = useTranslation(["common"]);
  const [selectedProcessId, setSelectedProcessId] = useState<number | null>(null);
  const [selectedMatchingStock, setSelectedMatchingStock] = useState<{
    jobOrderId: number;
    productProcessId: number;
  } | null>(null);
  const [tabIndex, setTabIndex] = useState(0);
  const { data: session } = useSession() as { data: SessionWithTokens | null };
  const currentUserId = session?.id ? parseInt(session.id) : undefined;

  // Add printer selection state
  const [selectedPrinter, setSelectedPrinter] = useState<PrinterCombo | null>(
    printerCombo && printerCombo.length > 0 ? printerCombo[0] : null
  );

  // 从 sessionStorage 恢复状态（仅在客户端）
  useEffect(() => {
    if (typeof window !== 'undefined') {
      try {
        const saved = sessionStorage.getItem(STORAGE_KEY);
        if (saved) {
          const parsed = JSON.parse(saved);
          // 验证数据有效性
          if (parsed && typeof parsed.jobOrderId === 'number' && typeof parsed.productProcessId === 'number') {
            setSelectedMatchingStock(parsed);
            console.log(" Restored selectedMatchingStock from sessionStorage:", parsed);
          }
        }
      } catch (error) {
        console.error("Error restoring selectedMatchingStock:", error);
        sessionStorage.removeItem(STORAGE_KEY);
      }
    }
  }, []);

  // 保存状态到 sessionStorage
  useEffect(() => {
    if (typeof window !== 'undefined') {
      if (selectedMatchingStock) {
        sessionStorage.setItem(STORAGE_KEY, JSON.stringify(selectedMatchingStock));
        console.log(" Saved selectedMatchingStock to sessionStorage:", selectedMatchingStock);
      } else {
        sessionStorage.removeItem(STORAGE_KEY);
      }
    }
  }, [selectedMatchingStock]);

  // 处理返回列表时清除存储
  const handleBackFromSecondScan = useCallback(() => {
    setSelectedMatchingStock(null);
    if (typeof window !== 'undefined') {
      sessionStorage.removeItem(STORAGE_KEY);
    }
  }, []);

  const handleTabChange = useCallback((event: React.SyntheticEvent, newValue: number) => {
    setTabIndex(newValue);
  }, []);

  if (selectedMatchingStock) {
    return (
      <JobPickExecutionsecondscan 
        filterArgs={{ jobOrderId: selectedMatchingStock.jobOrderId }}
        onBack={handleBackFromSecondScan}
      />
    );
  }
  
  if (selectedProcessId !== null) {
    return (
      <ProductionProcessJobOrderDetail
        jobOrderId={selectedProcessId}
        onBack={() => setSelectedProcessId(null)}
      />
    );
  }

  return (
    <Box>
      {/* Header section with printer selection */}
      {tabIndex === 1 && (
        <Box sx={{ 
          p: 1,
          borderBottom: '1px solid #e0e0e0',
          minHeight: 'auto',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'flex-end',
          gap: 2,
          flexWrap: 'wrap',
        }}>
          <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
              disableClearable
              options={printerCombo || []}
              getOptionLabel={(option) =>
                option.name || option.label || option.code || `Printer ${option.id}`
              }
              value={selectedPrinter || undefined}
              onChange={(_, newValue) => setSelectedPrinter(newValue)}
              sx={{ minWidth: 200 }}
              size="small"
              renderInput={(params) => (
                <TextField 
                  {...params} 
                  placeholder={t("Printer")}
                  inputProps={{
                    ...params.inputProps,
                    readOnly: true,
                  }}
                />
              )}
            />
          </Stack>
        </Box>
      )}

      <Tabs value={tabIndex} onChange={handleTabChange} sx={{ mb: 2 }}>
        <Tab label={t("Production Process")} />
        <Tab label={t("Finished QC Job Orders")} />
      </Tabs>

      {tabIndex === 0 && (
        <ProductionProcessList
          printerCombo={printerCombo}
          onSelectProcess={(jobOrderId) => {
            const id = jobOrderId ?? null;
            if (id !== null) {
              setSelectedProcessId(id);
            }
          }}
          onSelectMatchingStock={(jobOrderId, productProcessId) => {
            setSelectedMatchingStock({ 
              jobOrderId: jobOrderId || 0, 
              productProcessId: productProcessId || 0 
            });
          }}
        />
      )}

      {tabIndex === 1 && (
        <FinishedQcJobOrderList 
          printerCombo={printerCombo}
          selectedPrinter={selectedPrinter}
        />
      )}
    </Box>
  );
};

export default ProductionProcessPage;