import { r as reactExports, j as jsxRuntimeExports, E as compilerRuntimeExports } from "./vendor-react-DYNCg6N5.js";
import { c0 as CalendarIcon, cq as useLazyUpdateInvitationLinkQuery, cr as setToEndOFDate, cs as useDeleteInvitationLinkMutation, aV as EditIcon, aJ as CalendarExtraIcon, m as universalNotification, ct as useLazyCreateInvitationLinkQuery, c as useAppSelector, cu as useLazyGetInvitationLinksListQuery } from "./index-DfebxkL9.js";
import { u as useStyles } from "./styles-rKP3r-bS.js";
import { l as lG, C as ES } from "./vendor-icons-xWhXK_Ui.js";
import { c as copyToClipboard } from "./utils-D5kCyTRM.js";
import { f as formatDate } from "./date-bOIw2uwV.js";
import { g as getValidateErrors } from "./validation-Ds00Zghx.js";
import { u as useTranslation } from "./vendor-i18n-wisIXUFi.js";
import { z as useForm, b as Box, a0 as SimpleGrid, E as TextInput, as as DatePickerInput, B as Button, U as UnstyledButton, V as LoadingOverlay, s as showNotification, n as useDisclosure, W as useMediaQuery, F as Flex, T as Text, h as ActionIcon, k as Tooltip, at as Modal$1 } from "./vendor-mantine-h0WlM2Mj.js";
import { o as objectType, p as preprocessType, f as dateType, s as stringType } from "./types-espwwxTQ.js";
import { M as Modal } from "./index-DqcA8P_y.js";
import { A as AddButton } from "./index-72JBTuLT.js";
import "./styles-3NoIlzov.js";
import "./types-B9VC9FeZ.js";
const LinkInviteForm = ({
  handleChangeLink,
  invitationLink,
  isEditing,
  handleClose
}) => {
  const {
    classes
  } = useStyles();
  const {
    t,
    i18n
  } = useTranslation();
  const validateSchema = objectType({
    name: stringType().trim().min(2, {
      message: t("validation.enterLinkName")
    }).max(20, {
      message: t("validation.maxLengthSymbolsWithCount.symbols", {
        count: 20
      })
    }),
    date: preprocessType((arg) => arg instanceof Date ? arg : new Date(arg), dateType())
  });
  const form = useForm({
    initialValues: {
      name: "",
      date: /* @__PURE__ */ new Date()
    },
    validateInputOnChange: true,
    validate: (values) => getValidateErrors(validateSchema, values)
  });
  const errors = form.errors;
  const isDisabled = Object.keys(errors).length !== 0 || !form.isValid();
  reactExports.useEffect(() => {
    if (invitationLink) {
      const values_0 = {
        name: invitationLink.Name,
        date: new Date(invitationLink.ExpiredAt) || /* @__PURE__ */ new Date()
      };
      form.setValues(values_0);
      form.resetDirty(values_0);
    }
  }, [invitationLink]);
  const handleSubmit = async (values_1) => {
    var _a;
    try {
      const date = values_1.date instanceof Date ? values_1.date : new Date(values_1.date);
      await handleChangeLink({
        name: (_a = values_1 == null ? void 0 : values_1.name) == null ? void 0 : _a.trim(),
        date
      });
      form.reset();
    } catch (error) {
      console.error("Failed to submit invitation link form:", error);
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { className: classes.modalRoot, onSubmit: form.onSubmit(handleSubmit), children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { className: classes.modalContainer, sx: {
      paddingBottom: "24px"
    }, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(SimpleGrid, { cols: 1, w: "100%", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(TextInput, { className: classes.textFieldInput, label: t("filials.inviteLinks.linkName"), withAsterisk: true, ...form.getInputProps("name") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(DatePickerInput, { locale: i18n.language, className: classes.dateFieldInput, rightSection: /* @__PURE__ */ jsxRuntimeExports.jsx(CalendarIcon, {}), rightSectionPointerEvents: "none", minDate: /* @__PURE__ */ new Date(), label: t("filials.inviteLinks.validPeriod"), popoverProps: {
        withinPortal: true,
        zIndex: 1400
      }, ...form.getInputProps("date") })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { className: classes.modalFooter, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { w: "49%", type: "submit", disabled: isDisabled, children: t(`${isEditing ? "save" : "create"}`) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(UnstyledButton, { w: "49%", className: classes.modalCancelBtn, onClick: () => handleClose(), children: t("cancel") })
    ] })
  ] });
};
const EditLinkModalContent = ({
  handleChange,
  invitationLink,
  opened,
  handleClose,
  isEditing,
  CustomerId
}) => {
  const {
    t
  } = useTranslation();
  const [updateInvitationLink, {
    isError,
    isFetching
  }] = useLazyUpdateInvitationLinkQuery();
  const handleUpdateLink = async (values) => {
    var _a;
    try {
      const res = await updateInvitationLink({
        Name: values == null ? void 0 : values.name,
        ExpiredAt: setToEndOFDate(values == null ? void 0 : values.date),
        Code: (invitationLink == null ? void 0 : invitationLink.Code) || "",
        CustomerId
      });
      if (res.error) {
        showNotification({
          title: `${(_a = res == null ? void 0 : res.error) == null ? void 0 : _a.data}`,
          message: "",
          autoClose: true,
          color: "red",
          style: {
            zIndex: 1003
          }
        });
      } else if (res.data) {
        showNotification({
          title: t("filials.inviteLinks.linkSuccessEdited"),
          message: "",
          autoClose: true,
          color: "green",
          style: {
            zIndex: 1003
          }
        });
        handleClose();
        if (handleChange) {
          handleChange();
        }
      }
    } catch (err) {
      console.error("Failed to update invitation link:", err);
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(LinkInviteForm, { invitationLink, isEditing, handleChangeLink: handleUpdateLink, handleClose, opened, isFetching }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(LoadingOverlay, { visible: isFetching && !isError, overlayProps: {
      blur: 2
    } })
  ] });
};
const InviteLinkItem = ({
  invitationLink,
  handleChange,
  CustomerId
}) => {
  const {
    classes,
    theme
  } = useStyles();
  const {
    t
  } = useTranslation();
  const [openDeleteItemModal, setOpenDeleteItemModal] = reactExports.useState(false);
  const [opened, {
    open,
    close
  }] = useDisclosure(false);
  const [linkCopied, setLinkCopied] = reactExports.useState(false);
  const [deleteInvitationLink, {
    isLoading: deleteLinkLoading,
    isSuccess: deleteLinkSuccess,
    isError
  }] = useDeleteInvitationLinkMutation();
  const onClickDelete = async (e) => {
    var _a;
    e.preventDefault();
    try {
      const res = await deleteInvitationLink(invitationLink == null ? void 0 : invitationLink.Code);
      if (res.error) {
        showNotification({
          title: `${(_a = res == null ? void 0 : res.error) == null ? void 0 : _a.data}`,
          message: "",
          autoClose: true,
          color: "red",
          style: {
            zIndex: 1003
          }
        });
      } else {
        showNotification({
          title: t(`filials.inviteLinks.linkSuccessDeleted`),
          message: "",
          autoClose: true,
          color: "green",
          style: {
            zIndex: 1003
          }
        });
        handleCloseModal();
        if (handleChange) {
          handleChange();
        }
      }
    } catch (err) {
      console.error("Failed to delete invitation link:", err);
    }
  };
  reactExports.useEffect(() => {
    if (deleteLinkSuccess && !isError) {
      handleCloseModal();
      if (handleChange) {
        handleChange();
      }
    }
  }, [deleteLinkSuccess, isError]);
  const handleCloseModal = () => {
    setOpenDeleteItemModal(false);
  };
  const isMobile = useMediaQuery("(max-width: 992px)");
  const copyText = async () => {
    try {
      copyToClipboard(invitationLink.Url);
      setLinkCopied(true);
      universalNotification({
        isError: false,
        error: null,
        isSuccess: true,
        successTitle: t("copied")
      });
    } catch (e_0) {
      console.error("Failed to copy to clipboard:", e_0);
      setLinkCopied(false);
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(SimpleGrid, { cols: isMobile ? 1 : 2, mt: 16, w: "100%", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Flex, { w: "100%", align: "center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Text, { className: classes.mailText, w: "400px", children: invitationLink == null ? void 0 : invitationLink.Name }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Flex, { w: "100%", align: "center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(TextInput, { className: classes.linkInput, rightSection: invitationLink.Url && /* @__PURE__ */ jsxRuntimeExports.jsx(lG, { color: linkCopied ? "teal" : "blue", onClick: copyText }), value: invitationLink.Url, readOnly: true }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ActionIcon, { size: 24, mr: 20, ml: 20, onClick: () => open(), children: /* @__PURE__ */ jsxRuntimeExports.jsx(EditIcon, {}) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { sx: {
        background: "#FFF",
        boxShadow: "0px 8px 32px 0px rgba(0, 0, 0, 0.07)",
        borderRadius: theme.spacing.xs,
        padding: "8px"
      }, label: t(`filials.inviteLinks.${invitationLink.IsActive ? "validUntil" : "linkInactiveWasValidUntil"}`, {
        date: formatDate(invitationLink == null ? void 0 : invitationLink.ExpiredAt)
      }), zIndex: "1003", c: theme.colors.dark[8], children: /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { mr: 20, mt: "auto", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CalendarExtraIcon, { stroke: invitationLink.IsActive ? "#667085" : "#DE0E0E" }) }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { sx: {
        display: "flex",
        alignItems: "center"
      }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ActionIcon, { size: 24, onClick: () => setOpenDeleteItemModal(true), children: /* @__PURE__ */ jsxRuntimeExports.jsx(ES, { color: "#667085" }) }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Modal, { opened, onClose: close, title: t(`filials.inviteLinks.editingLink`), size: isMobile ? "90%" : "40%", children: /* @__PURE__ */ jsxRuntimeExports.jsx(EditLinkModalContent, { CustomerId, invitationLink, opened, handleClose: close, handleChange, isEditing: true }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Modal$1, { opened: openDeleteItemModal, onClose: () => setOpenDeleteItemModal(false), title: /* @__PURE__ */ jsxRuntimeExports.jsx(Text, { fw: 700, fz: "lg", children: t("warning") }), zIndex: 1002, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { mb: "1rem", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Text, { mb: "1rem", fz: "md", children: [
        t("filials.inviteLinks.warning"),
        ": ",
        /* @__PURE__ */ jsxRuntimeExports.jsx("b", { children: invitationLink == null ? void 0 : invitationLink.Name }),
        "?"
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(SimpleGrid, { cols: {
        base: 1,
        sm: 2
      }, mt: "md", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(UnstyledButton, { className: classes.modalCancelBtn, onClick: handleCloseModal, children: t("cancel") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { color: "red", bg: "#C23939", onClick: onClickDelete, children: t("continue") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(LoadingOverlay, { visible: deleteLinkLoading, overlayProps: {
        blur: 2
      } })
    ] })
  ] });
};
const CreateLinkModalContent = ({
  handleChange,
  invitationLink,
  opened,
  handleClose,
  isEditing,
  CustomerId
}) => {
  const {
    t
  } = useTranslation();
  const [createInvitationLink, {
    isError,
    isFetching
  }] = useLazyCreateInvitationLinkQuery();
  const handleSubmit = async (values) => {
    var _a;
    try {
      const res = await createInvitationLink({
        Name: values == null ? void 0 : values.name,
        ExpiredAt: setToEndOFDate(values == null ? void 0 : values.date),
        CustomerId
      });
      if (res.error) {
        showNotification({
          title: `${(_a = res == null ? void 0 : res.error) == null ? void 0 : _a.data}`,
          message: "",
          autoClose: true,
          color: "red",
          style: {
            zIndex: 1003
          }
        });
      } else if (res.data) {
        showNotification({
          title: t(`filials.inviteLinks.linkSuccessCreated`),
          message: "",
          autoClose: true,
          color: "green",
          style: {
            zIndex: 1003
          }
        });
        handleClose();
        if (handleChange) {
          handleChange();
        }
      }
    } catch (err) {
      console.error("Failed to create invitation link:", err);
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(LinkInviteForm, { invitationLink, isEditing, handleChangeLink: handleSubmit, handleClose, opened, isFetching }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(LoadingOverlay, { visible: isFetching && !isError, overlayProps: {
      blur: 2
    } })
  ] });
};
const CreateInviteLink = (t0) => {
  const $ = compilerRuntimeExports.c(26);
  const {
    handleChange,
    CustomerId
  } = t0;
  const [opened, t1] = useDisclosure(false);
  const {
    open,
    close
  } = t1;
  const {
    classes
  } = useStyles();
  const {
    t
  } = useTranslation();
  const isMobile = useMediaQuery("(max-width: 992px)");
  const t2 = classes.addButton;
  let t3;
  if ($[0] !== open) {
    t3 = () => open();
    $[0] = open;
    $[1] = t3;
  } else {
    t3 = $[1];
  }
  let t4;
  if ($[2] !== t) {
    t4 = t("filials.inviteLinks.createLink");
    $[2] = t;
    $[3] = t4;
  } else {
    t4 = $[3];
  }
  let t5;
  if ($[4] !== t4) {
    t5 = /* @__PURE__ */ jsxRuntimeExports.jsx(Text, { fw: "600", fz: "14", children: t4 });
    $[4] = t4;
    $[5] = t5;
  } else {
    t5 = $[5];
  }
  let t6;
  if ($[6] !== classes.addButton || $[7] !== t3 || $[8] !== t5) {
    t6 = /* @__PURE__ */ jsxRuntimeExports.jsx(AddButton, { className: t2, onClick: t3, children: t5 });
    $[6] = classes.addButton;
    $[7] = t3;
    $[8] = t5;
    $[9] = t6;
  } else {
    t6 = $[9];
  }
  let t7;
  if ($[10] !== t) {
    t7 = t("filials.inviteLinks.creatingLink");
    $[10] = t;
    $[11] = t7;
  } else {
    t7 = $[11];
  }
  const t8 = isMobile ? "90%" : "40%";
  let t9;
  if ($[12] !== CustomerId || $[13] !== close || $[14] !== handleChange || $[15] !== opened) {
    t9 = /* @__PURE__ */ jsxRuntimeExports.jsx(CreateLinkModalContent, { opened, handleClose: close, handleChange, isEditing: false, CustomerId });
    $[12] = CustomerId;
    $[13] = close;
    $[14] = handleChange;
    $[15] = opened;
    $[16] = t9;
  } else {
    t9 = $[16];
  }
  let t10;
  if ($[17] !== close || $[18] !== opened || $[19] !== t7 || $[20] !== t8 || $[21] !== t9) {
    t10 = /* @__PURE__ */ jsxRuntimeExports.jsx(Modal, { opened, onClose: close, title: t7, size: t8, children: t9 });
    $[17] = close;
    $[18] = opened;
    $[19] = t7;
    $[20] = t8;
    $[21] = t9;
    $[22] = t10;
  } else {
    t10 = $[22];
  }
  let t11;
  if ($[23] !== t10 || $[24] !== t6) {
    t11 = /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      t6,
      t10
    ] });
    $[23] = t10;
    $[24] = t6;
    $[25] = t11;
  } else {
    t11 = $[25];
  }
  return t11;
};
const InviteLinksList = () => {
  const {
    classes
  } = useStyles();
  const {
    t
  } = useTranslation();
  const {
    filial
  } = useAppSelector((state) => state.filials);
  const [getInvitationLinks, {
    data,
    isLoading
  }] = useLazyGetInvitationLinksListQuery();
  const handleChange = reactExports.useCallback(() => {
    (filial == null ? void 0 : filial.Id) && getInvitationLinks(filial.Id);
  }, [filial]);
  reactExports.useEffect(() => {
    if (!filial) {
      return;
    }
    if (filial.Id) {
      getInvitationLinks(filial.Id);
    }
  }, [filial]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { className: classes.container, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Flex, { className: classes.section, align: "flex-start", direction: "column", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Text, { className: classes.title, children: t("filials.inviteLinks.title") }),
    filial && (data == null ? void 0 : data.Invitations.length) ? data == null ? void 0 : data.Invitations.map((invitationLink, index) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(InviteLinkItem, { CustomerId: filial == null ? void 0 : filial.Id, invitationLink, handleChange }, index);
    }) : null,
    filial ? /* @__PURE__ */ jsxRuntimeExports.jsx(SimpleGrid, { cols: 1, mt: "sm", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CreateInviteLink, { handleChange, CustomerId: filial == null ? void 0 : filial.Id }) }) : null,
    /* @__PURE__ */ jsxRuntimeExports.jsx(LoadingOverlay, { visible: isLoading, overlayProps: {
      blur: 2
    } })
  ] }) });
};
export {
  InviteLinksList as default
};
//# sourceMappingURL=index-d-f5nm7J.js.map
