import { useCallback, useState } from "react";
import styles from "./styles.module.scss";
import { ChatsCategories, useApi, useApiCall } from "@/api";
import Loader, { LoaderColor } from "@/components/Loader";
import ChatsCategory from "../../components/ChatsCategory";
import AssistantOfDay from "../../components/AssistantOfDay";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { EAssistantStatus, IAssistant } from "@/api/resources/ChatsCategories";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";

function Categories() {
  const dispatch = useDispatch();
  const api = useApi();
  const navigate = useNavigate();
  const token = useSelector(selectors.selectToken);

  const [loadingAssistantId, setIsLoadingAssistantId] = useState<string>("");

  const assetsData = useCallback(async () => {
    const categories = await api.getChatsCategories(null);
    return categories;
  }, [api]);

  const { data, isPending } =
    useApiCall<ChatsCategories.ResponseGet>(assetsData);

  const createChat = async (assistantId: string) => {
    const response = await api.createChat({
      assistantId,
      token,
    });
    return response;
  };

  const handleAssistantClick = async (assistant: IAssistant) => {
    if (assistant.status === EAssistantStatus.BUSY) return;
    setIsLoadingAssistantId(assistant.id);
    try {
      const { chatId } = await createChat(assistant.id);
      dispatch(actions.chat.updateChatId(chatId));
      dispatch(actions.chat.updateAssistant(assistant));
      navigate(routes.client.chatsConnecting());
    } catch (error) {
      console.log(error);
    } finally {
      setIsLoadingAssistantId("");
    }
  };

  return (
    <section className={styles.container}>
      {isPending && (
        <Loader className={styles.loader} color={LoaderColor.White} />
      )}
      {!isPending &&
        // !error &&
        data?.categories &&
        data.categories.map((category, index) => (
          <div key={index}>
            <ChatsCategory
              loadingAssistantId={loadingAssistantId}
              category={category}
              handleAssistantClick={handleAssistantClick}
            />
            {index === 1 && data.categories.length > 1 && !!data.day && (
              <AssistantOfDay
                isLoading={loadingAssistantId === data.day.id}
                onAssistantClick={handleAssistantClick}
                assistant={data.day}
              />
            )}
            {data.categories.length <= 1 && !!data.day && (
              <AssistantOfDay
                isLoading={loadingAssistantId === data.day.id}
                onAssistantClick={handleAssistantClick}
                assistant={data.day}
              />
            )}
          </div>
        ))}
    </section>
  );
}

export default Categories;
