"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslation } from "react-i18next";
import { CreateItemInputs, saveItem } from "@/app/api/settings/item/actions";
import {
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
} from "react-hook-form";
import { deleteDialog } from "../Swal/CustomAlerts";
import {
  Box,
  Button,
  Grid,
  Stack,
  Tab,
  Tabs,
  TabsProps,
  Typography,
} from "@mui/material";
import { Check, Close, EditNote, ArrowBack } from "@mui/icons-material";
import { TypeEnum } from "@/app/utils/typeEnum";
import ProductDetails from "./ProductDetails";
import { CreateItemResponse } from "@/app/api/utils";
import QcDetails from "./QcDetails";
import { ItemQc } from "@/app/api/settings/item";
import { saveItemQcChecks } from "@/app/api/settings/qcCheck/actions";
import { useGridApiRef } from "@mui/x-data-grid";
import { QcCategoryCombo } from "@/app/api/settings/qcCategory";
import { WarehouseResult } from "@/app/api/warehouse";
import { softDeleteBagByItemId } from "@/app/api/bag/action";

type Props = {
  isEditMode: boolean;
  // type: TypeEnum;
  defaultValues: Partial<CreateItemInputs> | undefined;
  qcChecks: ItemQc[];
  qcCategoryCombo: QcCategoryCombo[];
  warehouses: WarehouseResult[];
};

const CreateItem: React.FC<Props> = ({
  isEditMode,
  // type,
  defaultValues,
  qcChecks,
  qcCategoryCombo,
  warehouses,
}) => {
  // console.log(type)
  const apiRef = useGridApiRef();
  const params = useSearchParams();
  console.log(params.get("id"));
  const [serverError, setServerError] = useState("");
  const [tabIndex, setTabIndex] = useState(0);
  const { t } = useTranslation("items");
  const router = useRouter();
  const title = "Product / Material";
  const [mode, redirPath] = useMemo(() => {
    // var typeId = TypeEnum.CONSUMABLE_ID
    let title = "";
    let mode = "";
    let redirPath = "";
    // if (type === TypeEnum.MATERIAL) {
    //   typeId = TypeEnum.MATERIAL_ID
    //   title = "Material";
    //   redirPath = "/settings/material";
    // }
    // if (type === TypeEnum.PRODUCT) {
    // typeId = TypeEnum.PRODUCT_ID
    title = "Product";
    redirPath = "/settings/items";
    // }
    // if (type === TypeEnum.BYPRODUCT) {
    //   typeId = TypeEnum.BYPRODUCT_ID
    //   title = "By-Product";
    //   redirPath = "/settings/byProduct";
    // }
    if (isEditMode) {
      mode = "Edit";
    } else {
      mode = "Create";
    }
    return [mode, redirPath];
  }, [isEditMode]);
  // console.log(typeId)
  const formProps = useForm<CreateItemInputs>({
    defaultValues: defaultValues ? defaultValues : {},
  });
  const errors = formProps.formState.errors;

  const handleTabChange = useCallback<NonNullable<TabsProps["onChange"]>>(
    (_e, newValue) => {
      setTabIndex(newValue);
    },
    [],
  );

  const handleCancel = () => {
    router.replace(`/settings/product`);
  };
  const onSubmit = useCallback<SubmitHandler<CreateItemInputs & {}>>(
    async (data, event) => {
      const hasErrors = false;
      console.log(errors);
      // console.log(apiRef.current.getCellValue(2, "lowerLimit"))
      // apiRef.current.
      try {
        if (hasErrors) {
          setServerError(t("An error has occurred. Please try again later."));
          return false;
        }
        
        // Normalize LocationCode: convert empty string to null
        if (data.LocationCode && data.LocationCode.trim() !== "") {
          // Parse LocationCode and populate store_id, warehouse, area, slot
          const parts = data.LocationCode.split("-");
          if (parts.length >= 4) {
            data.store_id = parts[0] || undefined;
            data.warehouse = parts[1] || undefined;
            data.area = parts[2] || undefined;
            data.slot = parts[3] || undefined;
          }
        } else {
          // If LocationCode is null or empty, set LocationCode to null and clear related fields
          data.LocationCode = undefined;
          data.store_id = undefined;
          data.warehouse = undefined;
          data.area = undefined;
          data.slot = undefined;
        }
        
        console.log("data posted");
        console.log(data);
        const qcCheck =
          data.qcChecks.length > 0
            ? data.qcChecks
                .filter((q) => data.qcChecks_active.includes(q.id!))
                .map((qc) => {
                  return {
                    qcItemId: qc.id,
                    instruction: qc.instruction,
                    lowerLimit: qc.lowerLimit,
                    upperLimit: qc.upperLimit,
                    itemId: parseInt(params.get("id")!.toString()),
                  };
                })
            : [];

        const test = data.qcChecks.filter((q) =>
          data.qcChecks_active.includes(q.id!),
        );
        // TODO:
        // 1. check field ( directly modify col def / check here )
        // 2. set error change tab index
        console.log(test);
        console.log(qcCheck);
        // return
        // do api
        const responseI = await saveItem(data);
      
        const responseQ = await saveItemQcChecks(qcCheck);
        if (responseI && responseQ) {
          if (!Boolean(responseI.id)) {
            formProps.setError(
              responseI.errorPosition! as keyof CreateItemInputs,
              {
                message: responseI.message!,
                type: "required",
              },
            );
          } else if (!Boolean(responseQ.id)) {
          } else if (Boolean(responseI.id) && Boolean(responseQ.id)) {
            // If special type is not "isBag", soft-delete the bag record if it exists
            if (data.isBag !== true && data.id) {
              try {
                const itemId = typeof data.id === "string" ? parseInt(data.id) : data.id;
                await softDeleteBagByItemId(itemId);
              } catch (bagError) {
                // Log error but don't block the save operation
                console.log("Error soft-deleting bag:", bagError);
              }
            }
            router.replace(redirPath);
          }
        }
      } catch (e) {
        // backend error
        setServerError(t("An error has occurred. Please try again later."));
        console.log(e);
      }
    },
    [apiRef, router, t],
  );

  // multiple tabs
  const onSubmitError = useCallback<SubmitErrorHandler<CreateItemInputs>>(
    (errors) => {},
    [],
  );

  return (
    <>
      <FormProvider {...formProps}>
        <Stack
          spacing={2}
          component="form"
          onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
        >
          <Grid>
            <Stack direction="column" spacing={1} mb={2}>
              <Button
                variant="outlined"
                startIcon={<ArrowBack />}
                onClick={() => router.push("/settings/items")}
                sx={{ alignSelf: "flex-start", minWidth: "auto" }}
              >
                {t("Back")}
              </Button>
              <Typography variant="h4">
                {t(`${mode} ${title}`)}
              </Typography>
            </Stack>
          </Grid>
          <Tabs
            value={tabIndex}
            onChange={handleTabChange}
            variant="scrollable"
          >
            <Tab label={t("Product / Material Details")} iconPosition="end" />
            {/* <Tab label={t("Qc items")} iconPosition="end" /> */}
          </Tabs>
          {serverError && (
            <Typography variant="body2" color="error" alignSelf="flex-end">
              {serverError}
            </Typography>
          )}
          {tabIndex === 0 && (
            <ProductDetails
              isEditMode={isEditMode}
              qcCategoryCombo={qcCategoryCombo}
              warehouses={warehouses}
              defaultValues={defaultValues}
            />
          )}
          {tabIndex === 1 && <QcDetails apiRef={apiRef} />}
          {/* {type === TypeEnum.MATERIAL && <MaterialDetails />} */}
          {/* {type === TypeEnum.BYPRODUCT && <ByProductDetails />} */}
          {/*
          <Stack direction="row" justifyContent="flex-end" gap={1}>
            <Button
              name="submit"
              variant="contained"
              startIcon={<Check />}
              type="submit"
            >
              {isEditMode ? t("Save") : t("Confirm")}
            </Button>
            <Button
              variant="outlined"
              startIcon={<Close />}
              onClick={handleCancel}
            >
              {t("Cancel")}
            </Button>
          </Stack>
          */}
        </Stack>
      </FormProvider>
    </>
  );
};
export default CreateItem;
