import { FC, Fragment } from 'react';
import { InfiniteQueryObserverBaseResult } from 'react-query';
import { useNavigate, useParams } from 'react-router-dom';

import { AxiosResponse } from 'axios';

import { useTranslation } from 'src/pages/dashboard/tickets/i18n';
import { ticketRoutes } from 'src/pages/dashboard/tickets/routes';
import { ChatListItem } from 'src/types/chats';
import { TicketsPaginationResponse } from 'src/types/tickets';

import { ThreadItem } from 'src/components/dashboard/chat/ThreadList';
import InfiniteList from 'src/components/list/InfiniteList';

export type TicketListProps = InfiniteQueryObserverBaseResult<
  AxiosResponse<TicketsPaginationResponse>
>;

const TicketList: FC<TicketListProps> = props => {
  const {
    data,
    isLoading,
    hasNextPage,
    fetchNextPage,
    isFetchingNextPage,
    ...others
  } = props;

  const { t } = useTranslation();
  const navigate = useNavigate();
  const { id } = useParams();
  const currentId = Number(id);

  const handleSelect = (thread: ChatListItem): void => {
    const { id: threadId } = thread.chat;
    const state = thread;

    navigate(ticketRoutes.thread.detail(threadId), { state });
  };

  const tikcetsPages = data?.pages || [];

  return (
    <InfiniteList
      isSuccess={!!tikcetsPages[0]?.data?.items.length}
      isEmpty={!tikcetsPages[0]?.data?.items.length}
      noResultsLabel={t('NO_TICKETS')}
      hasNextPage={hasNextPage}
      fetchNextPage={fetchNextPage}
      isFetchingNextPage={isFetchingNextPage}
      {...others}
    >
      {tikcetsPages.map((ticketPage, i) => (
        <Fragment key={i}>
          {ticketPage?.data?.items.map(thread => (
            <ThreadItem
              key={thread.chat.id}
              active={currentId === thread.chat.id}
              onClick={(): void => handleSelect(thread)}
              thread={thread}
            />
          ))}
        </Fragment>
      ))}
    </InfiniteList>
  );
};

export default TicketList;
