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;
};

const getOptimalColumns = (count: number) => {
  if (count <= 6) return count;
  return Math.ceil(count / 2);
};

export default function AdvisersSection({
  promiseAssistants,
  promiseChats,
  gridDisplayMode = "horizontal",
}: AdvisersSectionProps) {
  const assistants = use(promiseAssistants);
  const chats = use(promiseChats);

  if (!assistants || assistants.length === 0) {
    return null;
  }

  const columns = getOptimalColumns(assistants.length);

  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>
  );
}
