'use client';

import ChatCard, { ChatCardLayout } from './ChatCard';
import { IconPlus } from '../ui/Icons';
import { auth } from '@/auth';
import { ChatEntity } from '@/lib/types';
import { VariableSizeList as List } from 'react-window';
import { cleanInputMessage } from '@/lib/messageUtils';
import AutoSizer from 'react-virtualized-auto-sizer';

export interface ChatSidebarListProps {
  chats: ChatEntity[];
  isAdminView?: boolean;
}

const getItemSize = (message: string, isAdminView?: boolean) => {
  if (message.length >= 45) return 116;
  else if (message.length >= 20) return 104;
  else return 88;
};

export default async function ChatSidebarList({
  chats,
  isAdminView,
}: ChatSidebarListProps) {
  return (
    <>
      {!isAdminView && (
        <div className="p-2">
          <ChatCardLayout link="/chat">
            <div className="overflow-hidden flex items-center size-full">
              <IconPlus className="w-1/4 font-bold" />
              <p className="text-sm w-3/4 ml-3 font-bold">New chat</p>
            </div>
          </ChatCardLayout>
        </div>
      )}
      <AutoSizer>
        {({ height, width }) => (
          <List
            itemData={chats}
            height={height}
            itemCount={chats.length}
            itemSize={index =>
              getItemSize(
                cleanInputMessage(chats[index].messages?.[0]?.content ?? ''),
                isAdminView,
              )
            }
            width={width}
          >
            {({ style, index, data }) => (
              <div
                style={style}
                className="px-2 flex items-center overflow-hidden"
              >
                <ChatCard
                  key={data[index].id}
                  chat={data[index]}
                  isAdminView={isAdminView}
                />
              </div>
            )}
          </List>
        )}
      </AutoSizer>
    </>
  );
}
