"use client";

import {
  deleteQcCategory,
  saveQcCategory,
  SaveQcCategoryInputs,
} from "@/app/api/settings/qcCategory/actions";
import { Button, Stack } from "@mui/material";
import { useCallback } from "react";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import {
  deleteDialog,
  errorDialogWithContent,
  submitDialog,
  successDialog,
} from "../Swal/CustomAlerts";
import { useTranslation } from "react-i18next";
import { useRouter } from "next/navigation";
import QcCategoryDetails from "./QcCategoryDetails";
import { Check, Close, Delete } from "@mui/icons-material";

interface Props {
  defaultInputs?: SaveQcCategoryInputs;
}

const QcCategorySave: React.FC<Props> = ({ defaultInputs }) => {
  const { t } = useTranslation("qcCategory");
  const router = useRouter();

  const formProps = useForm<SaveQcCategoryInputs>({
    defaultValues: {
      ...defaultInputs,
    },
  });

  const handleSubmit = useCallback(async (data: SaveQcCategoryInputs) => {
    const response = await saveQcCategory(data);

    const errors = response.errors;
    if (errors) {
      let errorContents = "";
      for (const [key, value] of Object.entries(errors)) {
        formProps.setError(key as keyof SaveQcCategoryInputs, {
          type: "custom",
          message: value,
        });
        errorContents = errorContents + t(value) + "<br>";
      }

      errorDialogWithContent(t("Submit Error"), errorContents, t);
    } else {
      await successDialog(t("Submit Success"), t, () =>
        router.push("/settings/qcCategory"),
      );
    }
  }, []);

  const onSubmit = useCallback<SubmitHandler<SaveQcCategoryInputs>>(
    async (data) => {
      await submitDialog(() => handleSubmit(data), t);
    },
    [],
  );

  const handleCancel = () => {
    router.replace("/settings/qcCategory");
  };

  const handleDelete = () => {
    deleteDialog(async () => {
      await deleteQcCategory(formProps.getValues("id")!);

      await successDialog(t("Delete Success"), t, () =>
        router.replace("/settings/qcCategory"),
      );
    }, t);
  };

  return (
    <>
      <FormProvider {...formProps}>
        <Stack
          spacing={2}
          component={"form"}
          onSubmit={formProps.handleSubmit(onSubmit)}
        >
          <QcCategoryDetails />
          <Stack direction="row" justifyContent="flex-end" gap={1}>
            {defaultInputs?.id && (
              <Button
                variant="outlined"
                color="error"
                startIcon={<Delete />}
                onClick={handleDelete}
              >
                {t("Delete")}
              </Button>
            )}
            <Button
              variant="outlined"
              startIcon={<Close />}
              onClick={handleCancel}
            >
              {t("Cancel")}
            </Button>
            <Button
              name="submit"
              variant="contained"
              startIcon={<Check />}
              type="submit"
            >
              {t("Submit")}
            </Button>
          </Stack>
        </Stack>
      </FormProvider>
    </>
  );
};

export default QcCategorySave;
