"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 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;

  if (selectedMatchingStock) {
    return (
      <JobPickExecutionsecondscan 
        filterArgs={{ jobOrderId: selectedMatchingStock.jobOrderId }}
        onBack={() => setSelectedMatchingStock(null)}
      />
    );
  }
  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;