import React, { useRef, useState, useEffect } from "react";
import { Box, IconButton } from "@mui/material";
import TextareaAutosize from "react-textarea-autosize";
import { Button } from "../Button";
import SendIcon from "../../assets/chatBotSendIcon.svg";
import MicIcon from "../../assets/chatBotMicIcon.svg";
import RefreshIcon from "../../assets/chatBotRefreshIcon.svg";
import "./chatBot.style.scss";
import chatbotBannerIcon from "../../assets/chatbotBannerIcon.svg";
import ChatbotStopIcon from "../../assets/chatbotStopIcon.svg";
import ClearIcon from "@mui/icons-material/Clear";
import SaveOutlinedIcon from "@mui/icons-material/SaveOutlined";
import { Tooltip } from "../Tooltip";

const ChatInput = ({
  inputValue,
  setInputValue,
  setIsNewChat,
  onSendIconClick,
  setUserChats,
  userChats,
  handleRefresh,
  handleSaveChat,
  handleMicClick,
  activeList,
  uniqueId,
  suggestionBanner,
  isStopIcon,
  onStopIconClick,
  minRows = 1,
  newChatScreen = false,
  customScreen = false,
  onCloseSuggestionBanner,
  showSuggestionBanner,
  customInputComponent,
}) => {
  const inputRef = useRef(null);
  const [isFixed, setIsFixed] = useState(false);
  const [isScrollable, setIsScrollable] = useState(false);
  const [height, setHeight] = useState("auto");
  const MAX_HEIGHT = 142;

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

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

  const handleSendMessage = () => {
    setIsNewChat?.(false);
    setInputValue("");
    inputRef.current?.blur();
    let newUserChat = {
      id: userChats.length + 1,
      text: inputValue,
      role: "user",
      timestamp: new Date().toISOString(),
    };
    setUserChats((prev) => [...prev, newUserChat]);
    onSendIconClick?.(newUserChat, activeList, uniqueId);
  };

  const handleStopIconClick = () => {
    onStopIconClick?.(activeList);
  };

  return (
    <Box
      className={`chat-input-box ${newChatScreen ? "new-chat-screen" : ""} ${
        customScreen ? "custom-screen" : ""
      }`}
    >
      {showSuggestionBanner && (
        <div className="suggestion-banner">
          <div className="suggestion-banner-content">
            <img src={chatbotBannerIcon} />
            <span className="suggestion-banner-text">
              {suggestionBanner.freeTextContent}
            </span>
          </div>
          <IconButton
            size="small"
            onClick={onCloseSuggestionBanner}
            disableRipple
            sx={{ color: "#60697D" }}
          >
            <ClearIcon fontSize="16px" />
          </IconButton>
        </div>
      )}
      {customInputComponent ? (
        customInputComponent
      ) : (
        <div className="chat-input-container">
          <div
            className={`chat-input-wrapper ${isFixed ? "stacked" : ""} ${
              (!isFixed || inputValue === "") && !newChatScreen ? "empty" : ""
            } ${!newChatScreen && !isFixed ? "single-line-textarea" : ""}`}
            style={{ height: height }}
          >
            <TextareaAutosize
              ref={inputRef}
              minRows={minRows}
              className={`chat-textarea ${isScrollable ? "scrollable" : ""}`}
              placeholder="Ask anything..."
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onHeightChange={handleHeightChange}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  if (inputValue.trim().length > 0) {
                    handleSendMessage();
                  }
                }
              }}
            />

            {/* Buttons */}
            <div className={`chat-actions ${isFixed ? "fixed" : ""} `}>
              {handleRefresh && (
                <Button
                  icon={<img src={RefreshIcon} />}
                  iconPlacement="left"
                  size="large"
                  type="default"
                  variant="url"
                  onClick={handleRefresh}
                />
              )}
              {handleMicClick && (
                <Button
                  className=""
                  icon={<img src={MicIcon} />}
                  iconPlacement="left"
                  size="large"
                  type="default"
                  variant="tertiary"
                  onClick={handleMicClick}
                />
              )}

              {handleSaveChat && (
                <Tooltip title="Save Chat" variant="tertiary">
                  <Button
                    icon={<SaveOutlinedIcon />}
                    iconPlacement="left"
                    size="large"
                    type="default"
                    variant="tertiary"
                    onClick={handleSaveChat}
                    id="chat-input-save-button"
                  />
                </Tooltip>
              )}

              <Button
                icon={
                  !isStopIcon ? (
                    <img src={SendIcon} />
                  ) : (
                    <img src={ChatbotStopIcon} />
                  )
                }
                iconPlacement="left"
                size="large"
                type="default"
                variant="primary"
                onClick={!isStopIcon ? handleSendMessage : handleStopIconClick}
                id="chat-input-send-button"
                className={isStopIcon ? "stop-icon-button" : ""}
              />
            </div>
          </div>
        </div>
      )}
    </Box>
  );
};

export default ChatInput;
