import { useEffect } from 'react';
import { InfiniteQueryObserverResult } from 'react-query';

import { AxiosResponse } from 'axios';
import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import { type Theme } from '@material-hu/mui/styles';

import { GroupSchedulePost, GroupSchedulePostList } from 'src/types/groups';
import { Post } from 'src/types/posts';
import { CursorPagination } from 'src/types/services';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';
import { flatPages } from 'src/utils/pagination';

import { InfiniteList } from 'src/components/list';

import SchedulePost from './SchedulePost';
import useGroupScheduledPostsQuery from './useGroupScheduledPostsQuery';
import useScheduledPostsQuery from './useScheduledPostsQuery';

type UseScheduledPostsDrawerOptions = {
  groupId?: string;
  userCanSeePosts?: boolean;
};

export const getScheduledPostsDrawerConfig = ({
  t,
  scheduledPosts,
  isLoading,
  fetchNextPage,
  hasNextPage,
  isFetchingNextPage,
  closeDrawer,
}: {
  t: (key: string) => string;
  scheduledPosts: (Post | GroupSchedulePost)[];
  isLoading: boolean;
  hasNextPage: boolean | undefined;
  isFetchingNextPage: boolean;
  closeDrawer: () => void;
} & Pick<
  InfiniteQueryObserverResult<
    AxiosResponse<CursorPagination<Post[]> | GroupSchedulePostList>
  >,
  'fetchNextPage'
>) => ({
  title: t('scheduled_posts'),
  children: (
    <InfiniteList
      isSuccess={!!scheduledPosts}
      isLoading={isLoading}
      isEmpty={scheduledPosts?.length === 0}
      fetchNextPage={fetchNextPage}
      hasNextPage={hasNextPage ?? false}
      isFetchingNextPage={isFetchingNextPage}
      sx={(theme: Theme) => ({
        p: 2,
        position: 'relative',
        zIndex: 0,
        backgroundColor: theme.palette.new.background.layout.default,
        borderRadius: theme.shape.borderRadiusL,
      })}
    >
      {scheduledPosts.map((item, index) => (
        <SchedulePost
          key={item.id || index}
          post={item}
          onCloseModal={closeDrawer}
        />
      ))}
    </InfiniteList>
  ),
  onClose: closeDrawer,
});

const useScheduledPostsDrawer = (
  options: UseScheduledPostsDrawerOptions = {},
) => {
  const { groupId, userCanSeePosts = true } = options;
  const { t } = useTranslation('post');

  // Use different queries based on context
  const feedQuery = useScheduledPostsQuery();
  const groupQuery = useGroupScheduledPostsQuery(
    groupId || '',
    userCanSeePosts,
  );

  // Select the appropriate query result
  const { isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } = groupId
    ? groupQuery
    : feedQuery;

  // Flatten pages using the appropriate method and handle different data structures
  const scheduledPosts: (Post | GroupSchedulePost)[] = groupId
    ? flatPages(groupQuery.data)
    : flatPages(feedQuery.data);

  const {
    drawer,
    showDrawer,
    closeDrawer: closeDrawerFn,
  } = useDrawerV2(({ closeDrawer }) =>
    getScheduledPostsDrawerConfig({
      t,
      scheduledPosts,
      isLoading,
      fetchNextPage,
      hasNextPage,
      isFetchingNextPage,
      closeDrawer,
    }),
  );

  // Auto-close drawer when all scheduled posts are deleted
  useEffect(() => {
    if (!isLoading && scheduledPosts.length === 0) {
      closeDrawerFn();
    }
  }, [scheduledPosts.length, isLoading, closeDrawerFn]);

  return {
    drawer,
    showDrawer,
  };
};

export default useScheduledPostsDrawer;
