import { useEffect, useRef, useState } from "react"
import useStore from "../../utils/store"
import FileUploader from "../FileUploader"
import { SVGS } from "../../assets/svgs"
import { Message } from "../Message"
import { FileCard } from "../FileCard"
import { useTranslation } from "react-i18next"

export const Sidebar = ({
  // messages,
  sendPrompt,
  handleSubmit,
}: {
  // messages: TMessage[]
  sendPrompt: (prompt: string) => void
  handleSubmit: () => void
}) => {
  const { t } = useTranslation()

  const sidebarRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLTextAreaElement>(null)
  const uploadedFiles = useStore((state) => state.uploadedFiles)
  const setUploadedFiles = useStore((state) => state.setUploadedFiles)
  const messages = useStore((state) => state.messages)
  const [showBubble, setShowBubble] = useState(true)

  const [isOpen, setIsOpen] = useState(false)

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (
        isOpen &&
        sidebarRef.current &&
        !sidebarRef.current.contains(e.target as Node)
      ) {
        setIsOpen(false)
      }
    }
    document.addEventListener("mousedown", handleClickOutside)
    return () => document.removeEventListener("mousedown", handleClickOutside)
  }, [isOpen])
  return (
    <>
      {!isOpen && (
        <div className="fixed bottom-5 left-2 z-30 lg:hidden">
          {showBubble && (
            <div
              className={`flex flex-row gap-3 cloudy bg-white rounded-md p-2 shadow-md bg-learnpack-blue duration-500 border-2 border-blue-600 mb-4`}
            >
              <span className="w-[280px]">{t("sidebar.chatWithMe")}</span>
              <button
                className=" text-red-500 cursor-pointer bg-learnpack-blue p-2 rounded-md"
                onClick={() => setShowBubble(false)}
              >
                {SVGS.redClose}
              </button>
            </div>
          )}
          <button
            className="p-1 shadow-md cursor-pointer p-2 w-15 h-15 flex items-center justify-center bg-blue-600 rounded-[50%] fluid-svg"
            onClick={() => setIsOpen(true)}
          >
            {SVGS.rigoSoftBlue}
          </button>
        </div>
      )}

      <div
        ref={sidebarRef}
        className={`fixed z-30 top-0 left-0 h-full w-4/5 max-w-sm bg-learnpack-blue text-sm text-gray-700 border-r border-C8DBFC overflow-y-auto scrollbar-hide p-6 transition-transform duration-300 ease-in-out lg:relative lg:transform-none lg:w-1/3 ${
          isOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0"
        }`}
      >
        {isOpen && (
          <button
            className="lg:hidden bg-white p-1 rounded shadow-md mb-4 cursor-pointer absolute top-2 left-2"
            onClick={() => setIsOpen(false)}
          >
            ✕
          </button>
        )}

        <div className="space-y-2 pb-32 h-[85%] overflow-y-auto scrollbar-hide">
          {messages.map((message, index) => (
            <Message
              key={index}
              type={message.type}
              content={message.content}
            />
          ))}
        </div>

        <div className="relative w-full rounded-md bg-white text-gray-700 h-24">
          {uploadedFiles?.length > 0 && (
            <div className="absolute bottom-[100%] flex gap-2 w-full pb-1  rounded-md overflow-x-auto scrollbar-hide">
              {uploadedFiles.map((file, index) => (
                <FileCard
                  key={index}
                  file={file}
                  handleRemove={() => {
                    const newFiles = [...uploadedFiles]
                    newFiles.splice(index, 1)
                    setUploadedFiles(newFiles)
                  }}
                />
              ))}
            </div>
          )}
          <textarea
            ref={inputRef}
            style={{ resize: "none" }}
            className="w-full h-full p-2 outline-blue rounded"
            placeholder="How can Learnpack help you?"
            onKeyUp={(e) => {
              if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault()
                const val = inputRef.current?.value.trim() || ""

                if (val.toLowerCase() === "ok") {
                  handleSubmit()
                } else {
                  sendPrompt(val)
                }

                inputRef.current!.value = ""
              }
            }}
          />
          <div className="absolute bottom-2 right-2 flex gap-1 items-center">
            <FileUploader />
            <button
              className="cursor-pointer blue-on-hover flex items-center justify-center w-6 h-6"
              onClick={() => {
                if (inputRef.current?.value) {
                  const val = inputRef.current?.value.trim() || ""
                  if (val.toLowerCase() === "ok") {
                    handleSubmit()
                  } else {
                    sendPrompt(val)
                  }
                  inputRef.current!.value = ""
                }
              }}
            >
              {SVGS.send}
            </button>
          </div>
        </div>
      </div>
    </>
  )
}
