"use client";

import {
  deleteQcItem,
  saveQcItem,
  SaveQcItemInputs,
} from "@/app/api/settings/qcItem/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 QcItemDetails from "./QcItemDetails";
import { Check, Close, Delete } from "@mui/icons-material";

interface Props {
  defaultInputs?: SaveQcItemInputs;
}

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

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

  const handleSubmit = useCallback(async (data: SaveQcItemInputs) => {
    const response = await saveQcItem(data);

    const errors = response.errors;
    if (errors) {
      let errorContents = "";
      for (const [key, value] of Object.entries(errors)) {
        formProps.setError(key as keyof SaveQcItemInputs, {
          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/qcItem"),
      );
    }
  }, []);

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

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

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

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

  return (
    <>
      <FormProvider {...formProps}>
        <Stack
          spacing={2}
          component={"form"}
          onSubmit={formProps.handleSubmit(onSubmit)}
        >
          <QcItemDetails />
          <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 QcItemSave;
