"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslation } from "react-i18next";
import {
  CreateEquipmentInputs,
  saveEquipment,
} from "@/app/api/settings/equipment/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 } from "@mui/icons-material";
import { TypeEnum } from "@/app/utils/typeEnum";
import EquipmentDetails from "./EquipmentDetails";
import { CreateItemResponse } from "@/app/api/utils";
import { ItemQc } from "@/app/api/settings/item";
import { saveItemQcChecks } from "@/app/api/settings/qcCheck/actions";
import { useGridApiRef } from "@mui/x-data-grid";

type Props = {
  isEditMode: boolean;
  // type: TypeEnum;
  defaultValues: Partial<CreateEquipmentInputs> | undefined;
};

const CreateItem: React.FC<Props> = ({
  isEditMode,
  // type,
  defaultValues,
}) => {
  // 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(["equipment", "common"]);
  const router = useRouter();
  const title = "Equipment";
  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 = "Equipment";
    redirPath = "/settings/equipment";
    // }
    // 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<CreateEquipmentInputs>({
    defaultValues: defaultValues ? defaultValues : {},
  });
  const errors = formProps.formState.errors;

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

  const handleCancel = () => {
    router.replace(`/settings/equipment`);
  };
  const onSubmit = useCallback<SubmitHandler<CreateEquipmentInputs & {}>>(
    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;
        }
        console.log("data posted");
        console.log(data);

        // TODO:
        // 1. check field ( directly modify col def / check here )
        // 2. set error change tab index

        // return
        // do api
        console.log("asdad");
        const responseI = await saveEquipment(data);
        console.log("asdad");
        // var responseQ = await saveItemQcChecks(qcCheck)
        if (responseI) {
          if (!Boolean(responseI.id)) {
            formProps.setError(
              responseI.errorPosition! as keyof CreateEquipmentInputs,
              {
                message: responseI.message!,
                type: "required",
              },
            );
          } else if (Boolean(responseI.id)) {
            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<CreateEquipmentInputs>>(
    (errors) => {},
    [],
  );

  return (
    <>
      <FormProvider {...formProps}>
        <Stack
          spacing={2}
          component="form"
          onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
        >
          <Grid>
            <Typography mb={2} variant="h4">
              {t(`${mode} ${title}`)}
            </Typography>
          </Grid>
          <Tabs
            value={tabIndex}
            onChange={handleTabChange}
            variant="scrollable"
          >
            <Tab label={t("Equipment Details")} iconPosition="end" />
            {/* <Tab label={t("Qc items")} iconPosition="end" /> */}
          </Tabs>
          {serverError && (
            <Typography variant="body2" color="error" alignSelf="flex-end">
              {serverError}
            </Typography>
          )}
          {tabIndex === 0 && <EquipmentDetails isEditMode={isEditMode} />}
          {/* {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"
              //   disabled={submitDisabled}
            >
              {isEditMode ? t("Save") : t("Confirm")}
            </Button>
            <Button
              variant="outlined"
              startIcon={<Close />}
              onClick={handleCancel}
            >
              {t("Cancel")}
            </Button>
          </Stack>
          */}
        </Stack>
      </FormProvider>
    </>
  );
};
export default CreateItem;
