import GeneralLoading from "@/components/General/GeneralLoading";
import DetailedScheduleDetailView from "@/components/DetailedScheduleDetail/DetailedScheduleDetailView";
import { ScheduleType, fetchDetailedProdScheduleDetail } from "@/app/api/scheduling";

interface SubComponents {
  Loading: typeof GeneralLoading;
}

type EditDetailedScheduleDetailProps = {
  id?: number;
  type: ScheduleType;
};

type Props = EditDetailedScheduleDetailProps;

const DetailedScheduleDetailWrapper: React.FC<Props> & SubComponents = async ({
  id,
  type,
}) => {
  const prodSchedule = id ? await fetchDetailedProdScheduleDetail(id) : undefined;
  console.log("RAW API DATA:", prodSchedule?.prodScheduleLines[0]); // Check the actual keys here

  if (prodSchedule && prodSchedule.prodScheduleLines) {
    // 1. Map the lines to ensure the new fields are explicitly handled
    prodSchedule.prodScheduleLines = prodSchedule.prodScheduleLines.map(line => ({
      ...line,
      // If the API uses different names (e.g., 'stockQty'), map them here:
      // avgQtyLastMonth: line.avgQtyLastMonth ?? 0,
      
      // Ensure these keys match the 'field' property in your ViewByFGDetails.tsx columns
      avgQtyLastMonth: line.avgQtyLastMonth || 0, 
      stockQty: line.stockQty || 0,
      daysLeft: line.daysLeft || 0,
      needNoOfJobOrder: line.needNoOfJobOrder || 0,
      outputQty: line.outputQty || 0,
    })).sort((a, b) => b.priority - a.priority);
  }

  return (
    <DetailedScheduleDetailView
      isEditMode={Boolean(id)}
      defaultValues={prodSchedule}
      type={type}
    />
  );
};

DetailedScheduleDetailWrapper.Loading = GeneralLoading;

export default DetailedScheduleDetailWrapper;