"use client";
import React, { useState, useEffect, useCallback } from "react";
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig";
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 { 
  fetchProductProcesses, 
  fetchProductProcessesByJobOrderId,
  ProductProcessLineResponse 
} from "@/app/api/jo/actions";
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 [selectedProcessId, setSelectedProcessId] = useState<number | null>(null);
  const [selectedMatchingStock, setSelectedMatchingStock] = useState<{
    jobOrderId: number;
    productProcessId: number;
  } | null>(null);
  const { data: session } = useSession() as { data: SessionWithTokens | null };
  const currentUserId = session?.id ? parseInt(session.id) : undefined;

  // 从 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);
    }
  }, []);

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

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

export default ProductionProcessPage;