import React, { useState, useRef, useEffect } from "react";
import { Button } from "../../../../Button";
import { EditorToolbar } from "../../TextEditor/EditorToolbar";
// import CheckIcon from "@mui/icons-material/CheckRounded";
import ListIcon from "../../../../../assets/listIcon.svg";
import ThumbsUpIcon from "../../../../../assets/thumbsupBlueIcon.svg";
import CheckGreenIcon from "../../../../../assets/checkGreeIcon.svg";
import EditYellowIcon from "../../../../../assets/editYellowIcon.svg";
import DeleteRedIcon from "../../../../../assets/deleteRedIcon.svg";
import CheckBlueIcon from "../../../../../assets/checkBlueIcon.svg";
import WarningRedIcon from "../../../../../assets/warningRedIcon.svg";
import ThumbsUpYellowIcon from "../../../../../assets/thumbsUpYellowIcon.svg";
import NotAllowedGreenIcon from "../../../../../assets/notAllowedGreenIcon.svg";
import SendIcon from "../../../../../assets/sendIcon.svg";
import CheckIcon from "../../../../../assets/checkIcon.svg";
import SendDisabledIcon from "../../../../../assets/sendIconDisabled.svg";
import ChatCheckIcon from "../../../../../assets/ChatCheckIcon.svg";
// import TextareaAutosize from "react-textarea-autosize";
import { Box } from "@mui/material";
import { Menu } from "../../../../Menu";
import ImageUploader from "../ImageUploader/ImageUploader";
import FileUploader from "../FileUploader/FileUploader";
import TableChatEmojiPicker from "../EmojiPicker/EmojiPicker";
import "./ChatInput.styles.scss";
import { MentionEditor } from "../../TextEditor/Mention";

export const ChatInput = ({
  placeholder = "Type message",
  value,
  onChange,
  onSend,
  onAttach,
  onImageUpload,
  onEmojiClick,
  showFormatting = true,
  showQuickAction = true,
  quickActionLabel = "Quick action",
  disabled = false,
  maxLength = 5000,
  className = "chat-input",
  messageConfig = {},
  isEditMode = false,
  editingMessage = null,
  onCancelEdit,
  chatId,
}) => {
  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);
  const inputRef = 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 MAX_HEIGHT = 142;

  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: <img src={CheckBlueIcon} />,
      // onClick: (data) => {
      //   setSelectedPriority(data);
      // },
    },
    {
      value: "high",
      label: "High Priority",
      icon: <img src={WarningRedIcon} />,
      // onClick: (data) => {
      //   setSelectedPriority(data);
      // },
    },
    {
      value: "medium",
      label: "Medium Priority",
      icon: <img src={ThumbsUpYellowIcon} />,
      // onClick: (data) => {
      //   setSelectedPriority(data);
      // },
    },
    {
      value: "low",
      label: "Low Priority",
      icon: <img src={NotAllowedGreenIcon} />,
      // onClick: (data) => {
      //   setSelectedPriority(data);
      // },
    },
  ];

  const getPlainText = (html) => {
    // remove all tags and trim
    return html?.replace(/<[^>]+>/g, "")?.trim();
  };

  // Extract mentioned users from editor content
  const getMentionedUsers = () => {
    if (!editorRef.current?.editor) return [];

    const editor = editorRef.current.editor;
    const mentions = [];

    // Get all mention nodes from the editor
    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: <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: <img src={CheckGreenIcon} />,
      // onClick: (data) => {
      //   const text = getPrefillText(data);
      //   onChange?.(text);
      // },
      prefillText: "Sharing the final offer. Please confirm.",
    },
    {
      value: "editRequest",
      label: "Edit Request",
      icon: <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: <img src={DeleteRedIcon} />,
      // onClick: (data) => {
      //   const text = getPrefillText(data);
      //   onChange?.(text);
      // },
      prefillText: "Please delete this request from the list.",
    },
  ];

  const getPrefillText = (value, selectedArray) => {
    const action = selectedArray?.find((item) => item?.value === value);
    return action ? action : "";
  };

  const quickActionMenuOptions =
    messageConfig?.messageConfig?.quickActionProps?.length > 0
      ? messageConfig?.messageConfig?.quickActionProps
      : defaultQuickActionMenuOptions;

  const priorityMenuOptions =
    messageConfig?.messageConfig?.priorityOptions?.length > 0
      ? messageConfig?.messageConfig?.priorityOptions
      : priorityOptions;

  const updateFormatState = React.useCallback(() => {
    if (editorRef.current?.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 }),
        };
        // Only update if values actually changed
        return JSON.stringify(prev) === JSON.stringify(next) ? prev : next;
      });
    }
  }, []);

  // Compute the display value gracefully
  const getDisplayValue = () => {
    // Check if message has actual content (not just empty HTML tags)
    const plainText = getPlainText(message);
    if (plainText && plainText.trim() !== "") {
      return message;
    }
    // If no message but quick action has prefill text, use it
    if (
      selectedQuickAction?.prefillText &&
      selectedQuickAction.prefillText.trim() !== ""
    ) {
      setSelectedQuickAction(null);
      return "";
    }
    // Otherwise, return empty string
    return "";
  };

  // Get trimmed value for sending (HTML content)
  const getTrimmedValue = () => {
    // Return HTML content, but check if it has actual content (not just empty tags)
    const plainText = getPlainText(message);
    if (plainText && plainText.trim()) {
      return message; // Return HTML content
    }
    return selectedQuickAction?.prefillText?.trim() || "";
  };

  const handleInputChange = React.useCallback(
    (htmlContent) => {
      setMessage(htmlContent);
      onChange && onChange(htmlContent);
    },
    [onChange]
  );

  // Set up format state tracking
  useEffect(() => {
    let timeoutId;

    const handleSelectionUpdate = () => {
      // Clear any pending update
      if (timeoutId) {
        clearTimeout(timeoutId);
      }

      // Schedule a new update
      timeoutId = setTimeout(updateFormatState, 100);
    };

    // Add a small delay to ensure the editor is fully initialized
    const setupTimeout = setTimeout(() => {
      if (editorRef.current?.editor) {
        const editor = editorRef.current.editor;
        editor.on("selectionUpdate", handleSelectionUpdate);
        editor.on("update", handleSelectionUpdate);

        // Initial state update
        updateFormatState();
      }
    }, 100);

    return () => {
      clearTimeout(setupTimeout);
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      if (editorRef.current?.editor) {
        const editor = editorRef.current.editor;
        editor.off("selectionUpdate", handleSelectionUpdate);
        editor.off("update", handleSelectionUpdate);
      }
    };
  }, [updateFormatState]);

  const handleEmojiClick = (emoji) => {
    if (editorRef.current?.insertEmoji) {
      editorRef.current.insertEmoji(emoji);
    }
    setEmojiPickerOpen(false);
  };

  const handleSend = async () => {
    const htmlContent = getTrimmedValue();
    if (!htmlContent || disabled) return;

    // Extract mentioned users from the editor
    const mentionedUsers = getMentionedUsers();
    const taggedUsers = mentionedUsers.map((user) => user.id);
    if (onSend) {
      setIsSending(true);
      try {
        await onSend({
          content: htmlContent,
          selectedPriority,
          taggedUsers: taggedUsers,
        });
        // Clear the input after successful send
        setMessage("");
        setSelectedQuickAction(null);
        setSelectedPriority("");
        if (editorRef.current?.clearContent) {
          editorRef.current.clearContent();
        }
        onChange && onChange("");
      } catch (error) {
        console.error("Error sending message:", error);
        // Don't clear input if there was an error
      } finally {
        setIsSending(false);
      }
    } else {
      // If no onSend handler, still clear the input
      setMessage("");
      setSelectedQuickAction(null);
      if (editorRef.current?.clearContent) {
        editorRef.current.clearContent();
      }
      onChange && onChange("");
    }
  };

  // const formatText = (format) => {
  //   const textarea = textareaRef.current;
  //   if (!textarea) return;

  //   const start = textarea.selectionStart;
  //   const end = textarea.selectionEnd;
  //   const selectedText = message.substring(start, end);

  //   let formattedText = selectedText;
  //   switch (format) {
  //     case "bold":
  //       formattedText = `**${selectedText}**`;
  //       break;
  //     case "italic":
  //       formattedText = `*${selectedText}*`;
  //       break;
  //     case "link":
  //       formattedText = `[${selectedText}](url)`;
  //       break;
  //     default:
  //       break;
  //   }

  //   const newMessage =
  //     message.substring(0, start) + formattedText + message.substring(end);
  //   setMessage(newMessage);
  //   onChange && onChange(newMessage);
  // };

  const handleQuickActionClick = (event) => {
    setQuickActionMenuOpen(true);
    setQuickActionAnchorEl(event.currentTarget);
  };

  const handlePriorityClick = (event) => {
    setPriorityMenuOpen(true);
    setPriorityAnchorEl(event.currentTarget);
  };

  const handleUpload = (file) => {
    setIsLoading(true);
    setIsError(false);

    // Simulate a network request with a random success/failure response
    const isSuccess = Math.random() > 0.3; // 70% chance of success
    const apiResponseTime = 1500; // Simulate a 1.5 second network delay

    setTimeout(() => {
      setIsLoading(false);
      if (isSuccess) {
        // Create a URL for the selected file to display as a preview
        const imageUrl = URL.createObjectURL(file);
        setImage(imageUrl);
      } else {
        setIsError(true);
        console.error("Simulated API Error: Failed to upload image.");
      }
    }, apiResponseTime);
  };
  const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (file && file.type.startsWith("image/")) {
      const reader = new FileReader();
      reader.onload = (e) => {
        if (editorRef.current?.addImage) {
          editorRef.current.addImage(e.target.result, file.name);
        }
      };
      reader.readAsDataURL(file);

      // Reset input
      if (toolbarRef.current?.imageInput) {
        toolbarRef.current.imageInput.value = "";
      }
    }
  };

  const handleFileUpload = (event) => {
    const file = event.target.files[0];
    if (!file) return;

    setUploadedFile(file);
    setFileUploadLoading(true);
    setFileUploadError(false);

    // Simulate file upload API call
    setTimeout(() => {
      const isSuccess = Math.random() > 0.3; // 70% success rate
      setFileUploadLoading(false);

      if (isSuccess) {
        // Simulate a file URL from server
        const mockFileUrl = `https://api.example.com/files/${file.name}`;
        setFileUrl(mockFileUrl);
        console.log("File uploaded successfully:", mockFileUrl);
      } else {
        setFileUploadError(true);
        console.error("File upload failed");
      }
    }, 1500);

    // Reset input
    if (toolbarRef.current?.fileInput) {
      toolbarRef.current.fileInput.value = "";
    }
  };

  const handleFileRetry = () => {
    if (uploadedFile) {
      setFileUploadLoading(true);
      setFileUploadError(false);

      // Simulate retry
      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);
    // Reset the input value to allow the same file to be selected again
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  /**
   * Handles the retry button click, re-attempting the upload.
   */
  const handleRetry = () => {
    // Re-trigger the upload with the same file
    if (fileInputRef.current && fileInputRef.current.files[0]) {
      handleUpload(fileInputRef.current.files[0]);
    }
  };

  const handleFileDownload = (url, fileName) => {
    // In a real app, this would handle actual file download
    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); // Toggle the emoji picker
  };

  const handleHeightChange = (textareaHeight) => {
    if (textareaHeight) {
      if (textareaHeight > 40) {
        setIsFixed(true);
      }
      if (textareaHeight >= MAX_HEIGHT) {
        setIsScrollable(true);
      } else {
        setIsScrollable(false);
      }
      let newHeight = textareaHeight > 40 ? textareaHeight + 40 : "auto";
      if (newHeight !== "auto") {
        if (newHeight <= MAX_HEIGHT) {
          setHeight(newHeight);
        } else {
          setHeight(MAX_HEIGHT);
        }
      }
    }
  };

  useEffect(() => {
    if (message === "") {
      setHeight("auto");
      setIsFixed(false);
    }
  }, [message]);

  return (
    <div className={`${className} ${isFocused ? "focused" : ""}`}>
      {/* Edit Mode Indicator */}
      {isEditMode && editingMessage && (
        <div className="edit-mode-indicator">
          <div className="edit-mode-text">
            <span>✏️ Editing message</span>
            <button
              className="cancel-edit-btn"
              onClick={onCancelEdit}
              type="button"
            >
              Cancel
            </button>
          </div>
        </div>
      )}
      <div
        className={`quick-action-container ${
          showFormatting ? "show-formatting-enabled" : ""
        }`}
      >
        {showFormatting && (
          <EditorToolbar
            ref={toolbarRef}
            editor={editorRef.current}
            activeStates={isFormatActive}
            enabledItems={[
              "bold",
              "italic",
              "link",
              // "bulletList", // Enabled if required (functionality implemented)
              // "orderedList",
              "strike",
              "highlight",
              // "h1",
              // "h2",
              // "h3",
              // "h4",
              // "h5",
              // "h6",
            ]}
            // onFileSelect={handleFileUpload} // Enabled if required (functionality implemented)
            // onImageSelect={handleFileChange} // Enabled if required (functionality implemented)
            onEmojiSelect={handleEmojiPickerOpen}
            className="formatting-toolbar"
          />
        )}
        {showQuickAction && (
          <>
            <Button
              variant="tertiary"
              className={`${
                selectedQuickAction?.value && "selected_action_priority"
              } quick-action-button `}
              icon={<img src={ListIcon} />}
              onClick={handleQuickActionClick}
            >
              {quickActionLabel}
            </Button>
            <Menu
              anchorEl={quickActionAnchorEl}
              iconPlacement="top"
              open={quickActionMenuOpen}
              onClose={() => {
                setQuickActionMenuOpen(false);
              }}
              menuContainerClassName="quick-action-container"
              options={quickActionMenuOptions}
              MenuProps={{
                anchorOrigin: {
                  vertical: "top",
                  horizontal: "left",
                },
                transformOrigin: {
                  vertical: "bottom",
                  horizontal: "center",
                },
              }}
              selected={selectedQuickAction}
              onClick={(option) => {
                const text = getPrefillText(
                  option?.value,
                  quickActionMenuOptions
                );

                // If clicking the same option, deselect it
                if (selectedQuickAction?.value === option?.value) {
                  setSelectedQuickAction(null);
                  setMessage("");
                  if (editorRef.current?.clearContent) {
                    editorRef.current.clearContent();
                  }
                  onChange && "";
                } else {
                  // Set the new quick action and update editor content
                  setSelectedQuickAction(text);
                  const prefillText = text?.prefillText || "";
                  setMessage(prefillText);
                  // if (editorRef.current?.editor && prefillText) {
                  //   editorRef.current.editor.commands.setContent(prefillText);
                  // }
                  // onChange && onChange(prefillText);
                }
                setQuickActionMenuOpen(false);
              }}
            />
          </>
        )}
      </div>
      <div className="chat-input-section">
        <div className="chat-input-container">
          <div
            className={`chat-input-wrapper ${isFixed ? "stacked" : ""} ${
              !isFixed || message === "" ? "empty" : ""
            } ${!isFixed ? "single-line-textarea" : ""}`}
            style={{ height: height }}
          >
            <div className="message-input-container">
              <div className="upload-container">
                <div className="image-preview-container">
                  {image || isLoading || isError ? (
                    <ImageUploader
                      image={image}
                      isLoading={isLoading}
                      isError={isError}
                      handleClear={handleClear}
                      handleRetry={handleRetry}
                    />
                  ) : null}
                </div>
                <div className="file-preview-container">
                  {(uploadedFile || fileUploadLoading || fileUploadError) && (
                    <FileUploader
                      file={uploadedFile}
                      fileUrl={fileUrl}
                      isLoading={fileUploadLoading}
                      isError={fileUploadError}
                      onClear={handleFileClear}
                      onRetry={handleFileRetry}
                      onDownload={handleFileDownload}
                    />
                  )}
                </div>
              </div>
              <MentionEditor
                ref={editorRef}
                value={getDisplayValue()}
                onChange={handleInputChange}
                onSend={handleSend}
                placeholder="Type message... (mention users by typing @)"
                disabled={disabled}
                maxLength={maxLength}
                chatId={chatId}
                loadParticipantsAvatar={messageConfig?.loadParticipantsAvatar}
              />
            </div>
            <div className={`chat-actions ${isFixed ? "fixed" : ""}`}>
              <div className="input-actions">
                <div className="send-actions">
                  <Button
                    icon={<img src={CheckIcon} className="check-icon" />}
                    ariaLabel="Mark as done"
                    className={`${
                      selectedPriority?.value && "selected_action_priority"
                    } check-button`}
                    onClick={handlePriorityClick}
                    variant="tertiary"
                  />

                  <Menu
                    anchorEl={priorityAnchorEl}
                    iconPlacement="top"
                    open={priorityMenuOpen}
                    onClose={() => {
                      setPriorityMenuOpen(false);
                    }}
                    menuContainerClassName="priority-action-container"
                    MenuProps={{
                      anchorOrigin: {
                        vertical: "top",
                        horizontal: "left",
                      },
                      transformOrigin: {
                        vertical: "bottom",
                        horizontal: "right",
                      },
                    }}
                    options={priorityMenuOptions}
                    selected={selectedPriority}
                    onClick={(option) => {
                      const text = getPrefillText(
                        option?.value,
                        priorityMenuOptions
                      );
                      if (selectedPriority?.value === option?.value) {
                        setSelectedPriority("");
                      } else {
                        setSelectedPriority(text);
                      }

                      setPriorityMenuOpen(false);
                    }}
                  />
                  <Button
                    icon={<img src={SendIcon} />}
                    onClick={handleSend}
                    variant="primary"
                    disabled={!getTrimmedValue()}
                    aria-label={isEditMode ? "Update message" : "Send message"}
                    title={isEditMode ? "Update message" : "Send message"}
                    loading={isSending}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      {/* </div> */}
      <TableChatEmojiPicker
        open={emojiPickerOpen}
        onClose={handleEmojiPickerClose}
        onEmojiClick={handleEmojiClick}
        anchorEl={emojiAnchorEl}
      />
    </div>
  );
};
