import { useCallback, useState } from "react";
import { GoPerson, GoSignOut } from "react-icons/go";
import Button from "@/components/generics/button/Button";
import RequestTextArea from "@/components/views/requestTextArea/RequestTextArea";
import LlmAnswer from "@/components/views/llmAnswer/LlmAnswer";
import SearchResults from "@/components/views/search/searchResults/SearchResults";
import Loading from "@/components/generics/loading/Loading";
import SizeChanger from "@/components/generics/sizeChanger/SizeChanger";
import Comment from "@/components/views/comment/Comment";
import { FeedbackRequestType } from "@/api/predictions/types";
import LoginForm from "@/components/views/loginForm/LoginForm";
import "./Page.scss";
import { useAuth } from "@/shared/hooks/useAuth/useAuth";
import Tooltip from "@/components/generics/tooltip/Tooltip";
import { useAbbreviation } from "@/shared/hooks/useAbbreviations/useAbbreviation";
import { useGetChunks, useGetLlmResponse, usePostFeedback } from "@/api/predictions/hooks";

const Page = () => {
  const { userName, logout } = useAuth();
  const { content, setContent, textContent, textContentWithoutAbbrVal, abbreviationArray, addValues } =
    useAbbreviation();

  const [openAbbreviations, setOpenAbbreviations] = useState<boolean>(true);

  const { mutation: chunksMutation } = useGetChunks();
  const { mutate: getChunks, data: chunksData, isPending: isPendingChunks } = chunksMutation;

  const { mutation: llmMutation } = useGetLlmResponse();
  const { mutate: getLlm, data: llmData, isPending: isPendingLlm } = llmMutation;

  const { mutate: postFeedback, isPending: isPendingFeedback } = usePostFeedback();

  const handlePostFeedback = useCallback(
    (data: FeedbackRequestType, onSuccess?: () => void) => {
      postFeedback(data, {
        onSuccess: onSuccess,
      });
    },
    [postFeedback]
  );

  const handleGetPrediction = () => {
    getChunks(
      {
        userName: userName,
        query: textContentWithoutAbbrVal,
        query_abbreviation: textContent,
        abbreviations_replaced: abbreviationArray,
      },
      {
        onSuccess: (chunksResponse) => {
          if (chunksResponse) {
            getLlm({
              query: {
                userName: userName,
                query: textContentWithoutAbbrVal,
                query_abbreviation: textContent,
                abbreviations_replaced: abbreviationArray,
              },
              chunks: chunksResponse.chunks,
              chunksArray: chunksResponse.chunksArray,
            });
          }
        },
      }
    );
  };

  const handleLogout = () => {
    logout();
  };

  const handleEditRequest = () => {
    setOpenAbbreviations(true);
  };

  return (
    <div className="page">
      <div className="header_container">
        <h1 className="header">Поиск по документам</h1>
        <div className="user_container">
          <div className="user_name">
            <GoPerson />
            {userName}
          </div>
          <div className="logout">
            <Tooltip text="Выйти">
              <Button name="" onClick={handleLogout} icon={<GoSignOut color="red" />} buttonType="link" />
            </Tooltip>
          </div>
        </div>
      </div>
      <div className="search">
        <div className="search_block">
          <RequestTextArea
            openAbbreviations={openAbbreviations}
            content={content}
            setContent={setContent}
            abbreviationArray={abbreviationArray}
            handleEditRequest={handleEditRequest}
          />
          <div className="search_btns">
            <Button
              name="Поиск"
              onClick={() => {
                addValues();
                setOpenAbbreviations(false);
                handleGetPrediction();
              }}
              disabled={textContent.length === 0}
            />
          </div>
        </div>
      </div>
      {isPendingChunks && <Loading loading={isPendingChunks} />}
      {!isPendingChunks && chunksData && (
        <SizeChanger
          right={
            <SearchResults
              data={chunksData.chunksArray}
              documentsNumbers={llmData?.documentsNumbers}
              loading={isPendingChunks}
            />
          }
          left={
            <div className="llm_container">
              <LlmAnswer value={llmData?.answer_llm ?? ""} loading={isPendingLlm} />
              {!isPendingLlm && (
                <Comment onSubmit={handlePostFeedback} loading={isPendingFeedback} log_id={llmData?.log_id} />
              )}
            </div>
          }
        />
      )}
      <LoginForm />
    </div>
  );
};

export default Page;
