import { use } from "react";
import clsx from "clsx";

import { Grid, Section, Skeleton } from "@/components/ui";
import { IChat, IGetChatsListResponse } from "@/entities/chats/types";
import { Assistant } from "@/entities/dashboard/types";

import { AdviserCard } from "../../cards";

import styles from "./AdvisersSection.module.scss";

interface AdvisersSectionProps {
  promiseAssistants: Promise<Assistant[]>;
  promiseChats: Promise<IGetChatsListResponse>;
  gridDisplayMode?: "vertical" | "horizontal";
}

const getChatByAssistantId = (assistantId: string, chats: IChat[]) => {
  return chats.find(chat => chat.assistantId === assistantId) || null;
};

export default function AdvisersSection({
  promiseAssistants,
  promiseChats,
  gridDisplayMode = "horizontal",
}: AdvisersSectionProps) {
  const assistants = use(promiseAssistants);
  const chats = use(promiseChats);
  const columns = Math.ceil(assistants?.length / 2);

  return (
    <Section title="Advisers" contentClassName={styles.sectionContent}>
      <Grid
        columns={columns}
        className={clsx(styles.grid, styles[gridDisplayMode])}
      >
        {assistants.map(adviser => (
          <AdviserCard
            key={adviser._id}
            assistant={adviser}
            chat={getChatByAssistantId(
              adviser._id,
              chats.categorizedChats[adviser.category]
            )}
          />
        ))}
      </Grid>
    </Section>
  );
}

export function AdvisersSectionSkeleton() {
  return (
    <Section title="Advisers" contentClassName={styles.sectionContent}>
      <Skeleton className={styles.skeleton} />
    </Section>
  );
}
