import { jsxs, jsx, Fragment } from "react/jsx-runtime";
import React__default, { useState, useRef, useEffect } from "react";
import { getAssetUrl } from "../../../../../utils/assetBase.js";
import { Button } from "../../../../Button/index.js";
import { Menu } from "../../../../Menu/index.js";
import { EditorToolbar } from "../../TextEditor/EditorToolbar.js";
import { MentionEditor } from "../../TextEditor/Mention.js";
import TableChatEmojiPicker from "../EmojiPicker/EmojiPicker.js";
import FileUploader from "../FileUploader/FileUploader.js";
import ImageUploader from "../ImageUploader/ImageUploader.js";
/* empty css                      */
getAssetUrl("icons/ChatCheckIcon.svg");
const CheckBlueIcon = getAssetUrl("icons/checkBlueIcon.svg");
const CheckGreenIcon = getAssetUrl("icons/checkGreeIcon.svg");
const CheckIcon = getAssetUrl("icons/checkIcon.svg");
const DeleteRedIcon = getAssetUrl("icons/deleteRedIcon.svg");
const EditYellowIcon = getAssetUrl("icons/editYellowIcon.svg");
const ListIcon = getAssetUrl("icons/listIcon.svg");
const NotAllowedGreenIcon = getAssetUrl("icons/notAllowedGreenIcon.svg");
const ThumbsUpIcon = getAssetUrl("icons/thumbsupBlueIcon.svg");
const WarningRedIcon = getAssetUrl("icons/warningRedIcon.svg");
const ThumbsUpYellowIcon = getAssetUrl("icons/thumbsUpYellowIcon.svg");
const SendIcon = getAssetUrl("icons/sendIcon.svg");
getAssetUrl("icons/sendIconDisabled.svg");
const ChatInput = ({
  placeholder = "Type message",
  value,
  onChange,
  onSend,
  onAttach,
  onImageUpload,
  onEmojiClick,
  showFormatting = true,
  showQuickAction = true,
  quickActionLabel = "Quick action",
  disabled = false,
  maxLength = 5e3,
  className = "chat-input",
  messageConfig = {},
  isEditMode = false,
  editingMessage = null,
  onCancelEdit,
  chatId
}) => {
  var _a, _b, _c, _d, _e, _f;
  const [message, setMessage] = useState(value || "");
  const [isFocused, setIsFocused] = useState(false);
  const [quickActionAnchorEl, setQuickActionAnchorEl] = useState(null);
  const [quickActionMenuOpen, setQuickActionMenuOpen] = useState(false);
  const [priorityAnchorEl, setPriorityAnchorEl] = useState(null);
  const [priorityMenuOpen, setPriorityMenuOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isSending, setIsSending] = useState(false);
  const [isError, setIsError] = useState(false);
  const [image, setImage] = useState(null);
  const [uploadedFile, setUploadedFile] = useState(null);
  const [fileUrl, setFileUrl] = useState(null);
  const [fileUploadError, setFileUploadError] = useState(false);
  const [fileUploadLoading, setFileUploadLoading] = useState(false);
  const fileInputRef = useRef(null);
  const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);
  const [emojiAnchorEl, setEmojiAnchorEl] = useState(null);
  useRef(null);
  const [isFixed, setIsFixed] = useState(false);
  const [isScrollable, setIsScrollable] = useState(false);
  const [height, setHeight] = useState("auto");
  const [selectedPriority, setSelectedPriority] = useState("");
  const [selectedQuickAction, setSelectedQuickAction] = useState(null);
  const [isFormatActive, setIsFormatActive] = useState({
    bold: false,
    italic: false,
    link: false,
    bulletList: false,
    orderedList: false,
    strike: false,
    highlight: false,
    h1: false,
    h2: false,
    h3: false,
    h4: false,
    h5: false,
    h6: false
  });
  const editorRef = useRef(null);
  const toolbarRef = useRef(null);
  const priorityOptions = [
    {
      value: "normal",
      label: "Normal Priority",
      icon: /* @__PURE__ */ jsx("img", { src: CheckBlueIcon })
      // onClick: (data) => {
      //   setSelectedPriority(data);
      // },
    },
    {
      value: "high",
      label: "High Priority",
      icon: /* @__PURE__ */ jsx("img", { src: WarningRedIcon })
      // onClick: (data) => {
      //   setSelectedPriority(data);
      // },
    },
    {
      value: "medium",
      label: "Medium Priority",
      icon: /* @__PURE__ */ jsx("img", { src: ThumbsUpYellowIcon })
      // onClick: (data) => {
      //   setSelectedPriority(data);
      // },
    },
    {
      value: "low",
      label: "Low Priority",
      icon: /* @__PURE__ */ jsx("img", { src: NotAllowedGreenIcon })
      // onClick: (data) => {
      //   setSelectedPriority(data);
      // },
    }
  ];
  const getPlainText = (html) => {
    var _a2;
    return (_a2 = html == null ? void 0 : html.replace(/<[^>]+>/g, "")) == null ? void 0 : _a2.trim();
  };
  const getMentionedUsers = () => {
    var _a2;
    if (!((_a2 = editorRef.current) == null ? void 0 : _a2.editor)) return [];
    const editor = editorRef.current.editor;
    const mentions = [];
    editor.state.doc.descendants((node, pos) => {
      if (node.type.name === "mention") {
        mentions.push({
          id: node.attrs.id,
          label: node.attrs.label || node.attrs.id,
          position: pos
        });
      }
    });
    return mentions;
  };
  useEffect(() => {
    setMessage(value || "");
  }, [value]);
  const defaultQuickActionMenuOptions = [
    {
      value: "requestReview",
      label: "Request Review",
      icon: /* @__PURE__ */ jsx("img", { src: ThumbsUpIcon }),
      // onClick: (data) => {
      //   const text = getPrefillText(data);
      //   onChange?.(text);
      // },
      prefillText: "Please review this request and provide feedback."
    },
    {
      value: "finalOffer",
      label: "Final Offer",
      icon: /* @__PURE__ */ jsx("img", { src: CheckGreenIcon }),
      // onClick: (data) => {
      //   const text = getPrefillText(data);
      //   onChange?.(text);
      // },
      prefillText: "Sharing the final offer. Please confirm."
    },
    {
      value: "editRequest",
      label: "Edit Request",
      icon: /* @__PURE__ */ jsx("img", { src: EditYellowIcon }),
      // onClick: (data) => {
      //   const text = getPrefillText(data);
      //   onChange?.(text);
      // },
      prefillText: "I would like to request an edit for this item."
    },
    {
      value: "deleteRequest",
      label: "Delete Request",
      icon: /* @__PURE__ */ jsx("img", { src: DeleteRedIcon }),
      // onClick: (data) => {
      //   const text = getPrefillText(data);
      //   onChange?.(text);
      // },
      prefillText: "Please delete this request from the list."
    }
  ];
  const getPrefillText = (value2, selectedArray) => {
    const action = selectedArray == null ? void 0 : selectedArray.find((item) => (item == null ? void 0 : item.value) === value2);
    return action ? action : "";
  };
  const quickActionMenuOptions = ((_b = (_a = messageConfig.messageConfig) == null ? void 0 : _a.quickActionProps) == null ? void 0 : _b.length) > 0 ? (_c = messageConfig.messageConfig) == null ? void 0 : _c.quickActionProps : defaultQuickActionMenuOptions;
  const priorityMenuOptions = ((_e = (_d = messageConfig.messageConfig) == null ? void 0 : _d.priorityOptions) == null ? void 0 : _e.length) > 0 ? (_f = messageConfig.messageConfig) == null ? void 0 : _f.priorityOptions : priorityOptions;
  const updateFormatState = React__default.useCallback(() => {
    var _a2;
    if ((_a2 = editorRef.current) == null ? void 0 : _a2.editor) {
      const editor = editorRef.current.editor;
      setIsFormatActive((prev) => {
        const next = {
          bold: editor.isActive("bold"),
          italic: editor.isActive("italic"),
          link: editor.isActive("link"),
          bulletList: editor.isActive("bulletList"),
          orderedList: editor.isActive("orderedList"),
          strike: editor.isActive("strike"),
          highlight: editor.isActive("highlight"),
          h1: editor.isActive("heading", { level: 1 }),
          h2: editor.isActive("heading", { level: 2 }),
          h3: editor.isActive("heading", { level: 3 }),
          h4: editor.isActive("heading", { level: 4 }),
          h5: editor.isActive("heading", { level: 5 }),
          h6: editor.isActive("heading", { level: 6 })
        };
        return JSON.stringify(prev) === JSON.stringify(next) ? prev : next;
      });
    }
  }, []);
  const getDisplayValue = () => {
    const plainText = getPlainText(message);
    if (plainText && plainText.trim() !== "") {
      return message;
    }
    if ((selectedQuickAction == null ? void 0 : selectedQuickAction.prefillText) && selectedQuickAction.prefillText.trim() !== "") {
      setSelectedQuickAction(null);
      return "";
    }
    return "";
  };
  const getTrimmedValue = () => {
    var _a2;
    const plainText = getPlainText(message);
    if (plainText == null ? void 0 : plainText.trim()) {
      return message;
    }
    return ((_a2 = selectedQuickAction == null ? void 0 : selectedQuickAction.prefillText) == null ? void 0 : _a2.trim()) || "";
  };
  const handleInputChange = React__default.useCallback(
    (htmlContent) => {
      setMessage(htmlContent);
      onChange == null ? void 0 : onChange(htmlContent);
    },
    [onChange]
  );
  useEffect(() => {
    let timeoutId;
    const handleSelectionUpdate = () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      timeoutId = setTimeout(updateFormatState, 100);
    };
    const setupTimeout = setTimeout(() => {
      var _a2;
      if ((_a2 = editorRef.current) == null ? void 0 : _a2.editor) {
        const editor = editorRef.current.editor;
        editor.on("selectionUpdate", handleSelectionUpdate);
        editor.on("update", handleSelectionUpdate);
        updateFormatState();
      }
    }, 100);
    return () => {
      var _a2;
      clearTimeout(setupTimeout);
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      if ((_a2 = editorRef.current) == null ? void 0 : _a2.editor) {
        const editor = editorRef.current.editor;
        editor.off("selectionUpdate", handleSelectionUpdate);
        editor.off("update", handleSelectionUpdate);
      }
    };
  }, [updateFormatState]);
  const handleEmojiClick = (emoji) => {
    var _a2;
    if ((_a2 = editorRef.current) == null ? void 0 : _a2.insertEmoji) {
      editorRef.current.insertEmoji(emoji);
    }
    setEmojiPickerOpen(false);
  };
  const handleSend = async () => {
    var _a2, _b2;
    const htmlContent = getTrimmedValue();
    if (!htmlContent || disabled) return;
    const mentionedUsers = getMentionedUsers();
    const taggedUsers = mentionedUsers.map((user) => user.id);
    if (onSend) {
      setIsSending(true);
      try {
        await onSend({
          content: htmlContent,
          selectedPriority,
          taggedUsers
        });
        setMessage("");
        setSelectedQuickAction(null);
        setSelectedPriority("");
        if ((_a2 = editorRef.current) == null ? void 0 : _a2.clearContent) {
          editorRef.current.clearContent();
        }
        onChange == null ? void 0 : onChange("");
      } catch (error) {
        console.error("Error sending message:", error);
      } finally {
        setIsSending(false);
      }
    } else {
      setMessage("");
      setSelectedQuickAction(null);
      if ((_b2 = editorRef.current) == null ? void 0 : _b2.clearContent) {
        editorRef.current.clearContent();
      }
      onChange == null ? void 0 : onChange("");
    }
  };
  const handleQuickActionClick = (event) => {
    setQuickActionMenuOpen(true);
    setQuickActionAnchorEl(event.currentTarget);
  };
  const handlePriorityClick = (event) => {
    setPriorityMenuOpen(true);
    setPriorityAnchorEl(event.currentTarget);
  };
  const handleUpload = (file) => {
    setIsLoading(true);
    setIsError(false);
    const isSuccess = Math.random() > 0.3;
    const apiResponseTime = 1500;
    setTimeout(() => {
      setIsLoading(false);
      if (isSuccess) {
        const imageUrl = URL.createObjectURL(file);
        setImage(imageUrl);
      } else {
        setIsError(true);
        console.error("Simulated API Error: Failed to upload image.");
      }
    }, apiResponseTime);
  };
  const handleFileRetry = () => {
    if (uploadedFile) {
      setFileUploadLoading(true);
      setFileUploadError(false);
      setTimeout(() => {
        const isSuccess = Math.random() > 0.3;
        setFileUploadLoading(false);
        if (isSuccess) {
          const mockFileUrl = `https://api.example.com/files/${uploadedFile.name}`;
          setFileUrl(mockFileUrl);
          console.log("File upload retry successful:", mockFileUrl);
        } else {
          setFileUploadError(true);
          console.error("File upload retry failed");
        }
      }, 1500);
    }
  };
  const handleFileClear = () => {
    setUploadedFile(null);
    setFileUrl(null);
    setFileUploadError(false);
    setFileUploadLoading(false);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };
  const handleClear = () => {
    setImage(null);
    setIsLoading(false);
    setIsError(false);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };
  const handleRetry = () => {
    var _a2;
    if ((_a2 = fileInputRef.current) == null ? void 0 : _a2.files[0]) {
      handleUpload(fileInputRef.current.files[0]);
    }
  };
  const handleFileDownload = (url, fileName) => {
    console.log(`Downloading file ${fileName} from ${url}`);
  };
  const handleEmojiPickerClose = () => {
    setEmojiPickerOpen(false);
    setEmojiAnchorEl(null);
  };
  const handleEmojiPickerOpen = (event) => {
    event.preventDefault();
    event.stopPropagation();
    setEmojiAnchorEl(event.currentTarget);
    setEmojiPickerOpen(!emojiPickerOpen);
  };
  useEffect(() => {
    if (message === "") {
      setHeight("auto");
      setIsFixed(false);
    }
  }, [message]);
  return /* @__PURE__ */ jsxs("div", { className: `${className} ${isFocused ? "focused" : ""}`, children: [
    isEditMode && editingMessage && /* @__PURE__ */ jsx("div", { className: "edit-mode-indicator", children: /* @__PURE__ */ jsxs("div", { className: "edit-mode-text", children: [
      /* @__PURE__ */ jsx("span", { children: "✏️ Editing message" }),
      /* @__PURE__ */ jsx("button", { className: "cancel-edit-btn", type: "button", onClick: onCancelEdit, children: "Cancel" })
    ] }) }),
    /* @__PURE__ */ jsxs("div", { className: `quick-action-container ${showFormatting ? "show-formatting-enabled" : ""}`, children: [
      showFormatting && /* @__PURE__ */ jsx(
        EditorToolbar,
        {
          ref: toolbarRef,
          activeStates: isFormatActive,
          className: "formatting-toolbar",
          enabledItems: [
            "bold",
            "italic",
            "link",
            // "bulletList", // Enabled if required (functionality implemented)
            // "orderedList",
            "strike",
            "highlight"
            // "h1",
            // "h2",
            // "h3",
            // "h4",
            // "h5",
            // "h6",
          ],
          editor: editorRef.current,
          onEmojiSelect: handleEmojiPickerOpen
        }
      ),
      showQuickAction && /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          Button,
          {
            className: `${(selectedQuickAction == null ? void 0 : selectedQuickAction.value) && "selected_action_priority"} quick-action-button `,
            icon: /* @__PURE__ */ jsx("img", { src: ListIcon }),
            variant: "tertiary",
            onClick: handleQuickActionClick,
            children: quickActionLabel
          }
        ),
        /* @__PURE__ */ jsx(
          Menu,
          {
            anchorEl: quickActionAnchorEl,
            iconPlacement: "top",
            menuContainerClassName: "quick-action-container",
            MenuProps: {
              anchorOrigin: {
                vertical: "top",
                horizontal: "left"
              },
              transformOrigin: {
                vertical: "bottom",
                horizontal: "center"
              }
            },
            open: quickActionMenuOpen,
            options: quickActionMenuOptions,
            selected: selectedQuickAction,
            onClick: (option) => {
              var _a2;
              const text = getPrefillText(option.value, quickActionMenuOptions);
              if ((selectedQuickAction == null ? void 0 : selectedQuickAction.value) === option.value) {
                setSelectedQuickAction(null);
                setMessage("");
                if ((_a2 = editorRef.current) == null ? void 0 : _a2.clearContent) {
                  editorRef.current.clearContent();
                }
              } else {
                setSelectedQuickAction(text);
                const prefillText = (text == null ? void 0 : text.prefillText) || "";
                setMessage(prefillText);
              }
              setQuickActionMenuOpen(false);
            },
            onClose: () => {
              setQuickActionMenuOpen(false);
            }
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "chat-input-section", children: /* @__PURE__ */ jsx("div", { className: "chat-input-container", children: /* @__PURE__ */ jsxs(
      "div",
      {
        className: `chat-input-wrapper ${isFixed ? "stacked" : ""} ${!isFixed || message === "" ? "empty" : ""} ${!isFixed ? "single-line-textarea" : ""}`,
        style: { height },
        children: [
          /* @__PURE__ */ jsxs("div", { className: "message-input-container", children: [
            /* @__PURE__ */ jsxs("div", { className: "upload-container", children: [
              /* @__PURE__ */ jsx("div", { className: "image-preview-container", children: image || isLoading || isError ? /* @__PURE__ */ jsx(
                ImageUploader,
                {
                  handleClear,
                  handleRetry,
                  image,
                  isError,
                  isLoading
                }
              ) : null }),
              /* @__PURE__ */ jsx("div", { className: "file-preview-container", children: (uploadedFile || fileUploadLoading || fileUploadError) && /* @__PURE__ */ jsx(
                FileUploader,
                {
                  file: uploadedFile,
                  fileUrl,
                  isError: fileUploadError,
                  isLoading: fileUploadLoading,
                  onClear: handleFileClear,
                  onDownload: handleFileDownload,
                  onRetry: handleFileRetry
                }
              ) })
            ] }),
            /* @__PURE__ */ jsx(
              MentionEditor,
              {
                ref: editorRef,
                chatId,
                disabled,
                loadParticipantsAvatar: messageConfig.loadParticipantsAvatar,
                maxLength,
                placeholder: "Type message... (mention users by typing @)",
                value: getDisplayValue(),
                onChange: handleInputChange,
                onSend: handleSend
              }
            )
          ] }),
          /* @__PURE__ */ jsx("div", { className: `chat-actions ${isFixed ? "fixed" : ""}`, children: /* @__PURE__ */ jsx("div", { className: "input-actions", children: /* @__PURE__ */ jsxs("div", { className: "send-actions", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                ariaLabel: "Mark as done",
                className: `${selectedPriority.value && "selected_action_priority"} check-button`,
                icon: /* @__PURE__ */ jsx("img", { className: "check-icon", src: CheckIcon }),
                variant: "tertiary",
                onClick: handlePriorityClick
              }
            ),
            /* @__PURE__ */ jsx(
              Menu,
              {
                anchorEl: priorityAnchorEl,
                iconPlacement: "top",
                menuContainerClassName: "priority-action-container",
                MenuProps: {
                  anchorOrigin: {
                    vertical: "top",
                    horizontal: "left"
                  },
                  transformOrigin: {
                    vertical: "bottom",
                    horizontal: "right"
                  }
                },
                open: priorityMenuOpen,
                options: priorityMenuOptions,
                selected: selectedPriority,
                onClick: (option) => {
                  const text = getPrefillText(option.value, priorityMenuOptions);
                  if (selectedPriority.value === option.value) {
                    setSelectedPriority("");
                  } else {
                    setSelectedPriority(text);
                  }
                  setPriorityMenuOpen(false);
                },
                onClose: () => {
                  setPriorityMenuOpen(false);
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                "aria-label": isEditMode ? "Update message" : "Send message",
                disabled: !getTrimmedValue(),
                icon: /* @__PURE__ */ jsx("img", { src: SendIcon }),
                loading: isSending,
                title: isEditMode ? "Update message" : "Send message",
                variant: "primary",
                onClick: handleSend
              }
            )
          ] }) }) })
        ]
      }
    ) }) }),
    /* @__PURE__ */ jsx(
      TableChatEmojiPicker,
      {
        anchorEl: emojiAnchorEl,
        open: emojiPickerOpen,
        onClose: handleEmojiPickerClose,
        onEmojiClick: handleEmojiClick
      }
    )
  ] });
};
export {
  ChatInput
};
