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";
import { fetchWarehouseList } from "@/app/api/warehouse";
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);
    
    // Normalize LocationCode field (handle case sensitivity from MySQL)
    const locationCode = item?.LocationCode || item?.locationCode;
    
    console.log("Fetched item data for edit:", {
      id: item?.id,
      code: item?.code,
      name: item?.name,
      LocationCode: locationCode,
      rawItem: item
    });
    
    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,
      qcType: result.qcType,
      store_id: item?.store_id,
      warehouse: item?.warehouse,
      area: item?.area,
      slot: item?.slot,
      LocationCode: locationCode,
      isEgg: item?.isEgg,
      isFee: item?.isFee,
      isBag: item?.isBag,
    };
  }

  const qcCategoryCombo = await fetchQcCategoryCombo();
  const warehouses = await fetchWarehouseList();

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

export default CreateItemWrapper;
