import Title from "@/components/Title";
import styles from "./styles.module.css";
import { useCallback, useState } from "react";
import { Assistants, useApi, useApiCall } from "@/api";
import { useDispatch, useSelector } from "react-redux";
import { selectors } from "@/store";
import { IAssistant } from "@/api/resources/Assistants";
import AssistantCard from "./components/AssistantCard";
import Loader, { LoaderColor } from "@/components/Loader";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";

function Advisors() {
  const api = useApi();
  const dispatch = useDispatch();
  const token = useSelector(selectors.selectToken);
  const navigate = useNavigate();
  const [assistants, setAssistants] = useState<IAssistant[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const loadData = useCallback(async () => {
    const { ai_assistants } = await api.assistants({
      token,
    });
    setAssistants(ai_assistants);
    setIsLoading(false);
    return { ai_assistants };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [api, dispatch, token]);

  useApiCall<Assistants.Response>(loadData);

  const handleAdvisorClick = (assistant: IAssistant) => {
    navigate(routes.client.advisorChat(assistant.external_id));
  };

  return (
    <div className={`${styles.page} page`}>
      <Title variant="h1" className={styles.title}>
        Advisors
      </Title>
      {!!assistants?.length && !isLoading && (
        <div className={styles["advisors-container"]}>
          {assistants.map((assistant, index) => (
            <AssistantCard
              key={index}
              {...assistant}
              onClickCard={() => handleAdvisorClick(assistant)}
            />
          ))}
        </div>
      )}
      {isLoading && (
        <Loader color={LoaderColor.Red} className={styles.loader} />
      )}
    </div>
  );
}

export default Advisors;
