import { createPickOrder, SavePickOrderRequest } from "@/app/api/pickOrder/actions";
import { Box, Button, Modal, ModalProps, Stack } from "@mui/material";
import dayjs from "dayjs";
import arraySupport from "dayjs/plugin/arraySupport";
import { useCallback } from "react";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import CreateForm from "./CreateForm";
import { ItemCombo } from "@/app/api/settings/item/actions";
import { Check } from "@mui/icons-material";
dayjs.extend(arraySupport);

const style = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  overflow: "scroll",
  bgcolor: "background.paper",
  pt: 5,
  px: 5,
  pb: 10,
  display: "block",
  width: { xs: "100%", sm: "100%", md: "100%" },
};

interface Props extends Omit<ModalProps, "children"> {
    items: ItemCombo[]
}

const CreatePickOrderModal: React.FC<Props> = ({ 
    open,
    onClose,
    items
 }) => {
  const { t } = useTranslation("pickOrder");
  const formProps = useForm<SavePickOrderRequest>();
  const errors = formProps.formState.errors;
  const closeHandler = useCallback<NonNullable<ModalProps["onClose"]>>(
    (...args) => {
      onClose?.(...args);
      //   reset();
    },
    [onClose]
  );
  const onSubmit = useCallback<SubmitHandler<SavePickOrderRequest>>(
    async (data, event) => {
      console.log(data)
      try {
        const res = await createPickOrder(data)
        if (res.id) {
          closeHandler({}, "backdropClick");
        }
      } catch (error) {
        console.log(error)
        throw error
      }
      // formProps.reset()
    },
    [closeHandler]
  );
  return (
    <>
      <FormProvider {...formProps}>
        <Modal open={open} onClose={closeHandler}>
          <Box
            sx={style}
            component="form"
            onSubmit={formProps.handleSubmit(onSubmit)}
          >
            <CreateForm
                items={items}
            />
            <Stack direction="row" justifyContent="flex-end" gap={1}>
                <Button
                  name="submit"
                  variant="contained"
                  startIcon={<Check />}
                  type="submit"
                >
                  {t("submit")}
                </Button>
                <Button
                  name="reset"
                  variant="contained"
                  startIcon={<Check />}
                  onClick={() => formProps.reset()}
                >
                  {t("reset")}
                </Button>
            </Stack>
          </Box>
        </Modal>
      </FormProvider>
    </>
  );
};
export default CreatePickOrderModal;
