import { useCallback, useMemo } from "react";
import "./RequestTextArea.scss";
import Editable from "@/components/generics/editable/Editable";
import Spinner from "@/components/generics/spinner/Spinner";
import { filterMatches, getAllMatches, highlightMatches } from "@/shared/utils/highlightMatches";
import { AbbreviationsBlock } from "../abbreviationBlock/AbbreviationsBlock";
import RequestTextAreaProps from "./RequestTextAreaProps";
import { useAppSelector } from "@/store/hooks";
import { useGetAbbreviations } from "@/api/predictions/hooks";

const RequestTextArea = ({
  openAbbreviations,
  content,
  setContent,
  abbreviationArray,
  handleEditRequest,
}: RequestTextAreaProps) => {
  const { hasAbbreviations } = useAppSelector((state) => state.request);
  const { data: abbreviationsData, isLoading } = useGetAbbreviations();

  const sortedAbbreviations = useMemo(
    () => Object.keys(abbreviationsData ?? {}).sort((a, b) => b.length - a.length),
    [abbreviationsData]
  );

  const onContentChange = useCallback(
    (divContent: string) => {
      const initialRequest = divContent;
      const newContent = initialRequest.toString().replace(/\s+/g, " ");

      const allMatches: { match: string; index: number; element: string }[] = getAllMatches(
        sortedAbbreviations,
        newContent
      );
      const resultString = highlightMatches(newContent, filterMatches(allMatches));

      if (newContent !== content) {
        setContent(resultString === "<br>" ? "" : resultString);
      }

      handleEditRequest();
    },
    [content, handleEditRequest, setContent, sortedAbbreviations]
  );

  return (
    <div className="request_block">
      <div className="label">
        <span>Строка запроса</span>
      </div>
      <div className="request_container">
        <Editable
          content={content}
          handleClick={!openAbbreviations && hasAbbreviations ? handleEditRequest : undefined}
          onContentChange={onContentChange}
          className={!openAbbreviations && hasAbbreviations ? "clickable" : ""}
          placeholder="Введите запрос поиска. Например, какие действия являются первоочередными в момент обнаружения происшествия?"
        />
        {openAbbreviations && hasAbbreviations ? (
          <>
            <hr />
            {[...new Set(abbreviationArray)].map((abbr, index) => (
              <AbbreviationsBlock key={abbr + index} abbreviation={abbr} values={abbreviationsData?.[abbr] ?? []} />
            ))}
          </>
        ) : null}
      </div>
      <div className="abbr_message">
        {isLoading ? (
          <>
            <Spinner />
            <span>Загрузка аббревиатур</span>
          </>
        ) : null}
      </div>
    </div>
  );
};
export default RequestTextArea;
