import { TypeEnum } from "@/app/utils/typeEnum";
import CreateItem from "./CreateItem";
import CreateItemLoading from "./CreateItemLoading";
import { CreateItemInputs } from "@/app/api/settings/item/actions";
import { notFound } from "next/navigation";
import { fetchItem } from "@/app/api/settings/item";
import { fetchQcItems } from "@/app/api/settings/qcItem";
import { fetchQcCategoryCombo } from "@/app/api/settings/qcCategory";
interface SubComponents {
  Loading: typeof CreateItemLoading;
}

type Props = {
  id?: number;
  // type: TypeEnum;
};

const CreateItemWrapper: React.FC<Props> & SubComponents = async ({ id }) => {
  let result;
  let defaultValues: Partial<CreateItemInputs> | undefined;
  // console.log(type)
  let qcChecks;
  if (id) {
    result = await fetchItem(id);
    const item = result.item;
    qcChecks = result.qcChecks;
    const activeRows = qcChecks.filter((it) => it.isActive).map((i) => i.id);
    console.log(qcChecks);
    defaultValues = {
      type: item?.type,
      id: item?.id,
      code: item?.code,
      name: item?.name,
      description: item?.description,
      remarks: item?.remarks,
      shelfLife: item?.shelfLife,
      countryOfOrigin: item?.countryOfOrigin,
      maxQty: item?.maxQty,
      qcChecks: qcChecks,
      qcChecks_active: activeRows,
      qcCategoryId: item.qcCategory?.id
    };
  }

  const qcCategoryCombo = await fetchQcCategoryCombo();

  return (
    <CreateItem
      isEditMode={Boolean(id)}
      defaultValues={defaultValues}
      qcChecks={qcChecks || []}
      qcCategoryCombo={qcCategoryCombo}
    />
  );
};
CreateItemWrapper.Loading = CreateItemLoading;

export default CreateItemWrapper;
