"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslation } from "react-i18next";
import {
  CreateMaterialInputs,
  CreateProductMaterialResponse,
  saveMaterial,
} from "@/app/api/settings/material/actions";
import {
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
} from "react-hook-form";
import { deleteDialog } from "../Swal/CustomAlerts";
import { Box, Button, Grid, Stack, Typography } from "@mui/material";
import { Check, Close, EditNote } from "@mui/icons-material";
import { TypeEnum } from "@/app/utils/typeEnum";
import {
  CreateProductInputs,
  saveProduct,
} from "@/app/api/settings/product/actions";
import { CreateInputsFields } from "./CreateProductMaterialWrapper";
import MaterialDetails from "./MaterialDetails";
import ProductDetails from "./ProductDetails";

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

const CreateProductMaterial: React.FC<Props> = ({
  isEditMode,
  type,
  defaultValues,
}) => {
  const [serverError, setServerError] = useState("");
  const [tabIndex, setTabIndex] = useState(0);
  const { t } = useTranslation();
  const router = useRouter();
  const [title, mode, redirPath] = useMemo(() => {
    var title = "";
    var mode = "";
    var redirPath = "";
    if (type === TypeEnum.MATERIAL) {
      title = "Material";
      redirPath = "/material";
    }
    if (type === TypeEnum.PRODUCT) {
      title = "Product";
      redirPath = "/product";
    }
    if (isEditMode) {
      mode = "Edit";
    } else {
      mode = "Create";
    }
    return [title, mode, redirPath];
  }, [type, isEditMode]);

  const formProps = useForm<CreateInputsFields>({
    defaultValues: defaultValues ? defaultValues : {},
  });
  const errors = formProps.formState.errors;

  const handleCancel = () => {
    router.replace(`/settings/${type}`);
  };
  const onSubmit = useCallback<SubmitHandler<CreateInputsFields>>(
    async (data, event) => {
      let hasErrors = false;
      try {
        // checking humid input
        if (data.maxHumid && data.minHumid!! > data.maxHumid!!) {
          const message = "minHumid should not be greater than maxHumid";
          formProps.setError("minHumid", {
            message: message,
            type: "required",
          });
          formProps.setError("maxHumid", {
            message: message,
            type: "required",
          });
          hasErrors = true;
        }
        // checking temp input
        if (data.maxTemp && data.minTemp!! > data.maxTemp!!) {
          const message = "minTemp should not be greater than maxTemp";
          formProps.setError("minTemp", {
            message: message,
            type: "required",
          });
          formProps.setError("maxTemp", {
            message: message,
            type: "required",
          });
          hasErrors = true;
        }
        // checking passing rate
        if (data.passingRate && data.passingRate > 100) {
          const message = "passingRate should not be greater than 100%";
          formProps.setError("passingRate", {
            message: message,
            type: "required",
          });
        }
        // checking sampling rate
        if (data.sampleRate && data.sampleRate > 100) {
          const message = "sampleRate should not be greater than 100%";
          formProps.setError("sampleRate", {
            message: message,
            type: "required",
          });
        }
        if (hasErrors) {
          setServerError(t("An error has occurred. Please try again later."));
          return false;
        }
        console.log("data posted");
        console.log(data);
        // do api
        var response: CreateProductMaterialResponse | undefined;
        if (type === TypeEnum.MATERIAL) {
          response = await saveMaterial(data as CreateMaterialInputs);
        } else if (type === TypeEnum.PRODUCT) {
          response = await saveProduct(data as CreateProductInputs);
        }
        if (response) {
          if (!Boolean(response.id)) {
            formProps.setError(response.errorPosition!!, {
              message: response.message!!,
              type: "required",
            });
            throw response;
          } else if (Boolean(response.id)) {
            router.replace(redirPath);
          }
        } else {
          throw "no response";
        }
      } catch (e) {
        // backend error
        setServerError(t("An error has occurred. Please try again later."));
        console.log(e);
      }
    },
    [router, t]
  );

  // multiple tabs
  const onSubmitError = useCallback<SubmitErrorHandler<CreateInputsFields>>(
    (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>
          {serverError && (
            <Typography variant="body2" color="error" alignSelf="flex-end">
              {serverError}
            </Typography>
          )}
          {type === TypeEnum.MATERIAL && <MaterialDetails />}
          {type === TypeEnum.PRODUCT && <ProductDetails />}
          <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 CreateProductMaterial;
