import { useState } from 'react';
import { useInfiniteQuery } from 'react-query';

import { type AxiosResponse } from 'axios';
import { useDebounce } from '@material-hu/hooks/useDebounce';
import { useDrawer } from '@material-hu/hooks/useDrawer';
import { IconZoomExclamation } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import HuStateCard from '@material-hu/components/composed-components/StateCard';
import HuUserAvatar from '@material-hu/components/composed-components/UserAvatar';
import HuAlert from '@material-hu/components/design-system/Alert';
import HuSearch from '@material-hu/components/design-system/Inputs/Search';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { getAudiencesSearch } from 'src/services/audiencesService';
import { type AudienceCriteria, CriteriaType } from 'src/types/audience';
import { type RequestCursorPagination } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

export type NewSeeCollaboratorsProps = {
  // biome-ignore lint/suspicious/noExplicitAny: Not included as part of the scope of this ticket
  service: (pagination: RequestCursorPagination) => Promise<AxiosResponse<any>>;
  // biome-ignore lint/suspicious/noExplicitAny: Not included as part of the scope of this ticket
  queryKey: any[];
};

const NewSeeCollaborators = (props: NewSeeCollaboratorsProps) => {
  const HuGoThemeProvider = useHuGoTheme();
  const { service, queryKey } = props;
  const { t } = useLokaliseTranslation('audience');
  const [search, setSearch] = useState('');
  const debouncedSearch = useDebounce(search);

  const { data, isLoading, fetchNextPage, isFetchingNextPage, hasNextPage } =
    useInfiniteQuery(
      [queryKey, debouncedSearch],
      ({ pageParam }) =>
        service({
          q: debouncedSearch || undefined,
          limit: 10,
          cursor: pageParam,
        }),
      {
        getNextPageParam: lastPage => {
          if (lastPage.data.cursor) {
            return lastPage.data.cursor;
          }
          return undefined;
        },
      },
    );

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

  const results = formsPages.flatMap(page => page.data.items || []);

  return (
    <HuGoThemeProvider>
      <Stack sx={{ height: '100%' }}>
        <Stack sx={{ flex: 1, gap: 2 }}>
          <HuSearch
            value={search}
            onChange={setSearch}
          />
          <InfiniteList
            isSuccess={!!data}
            isLoading={isLoading}
            fetchNextPage={fetchNextPage}
            isFetchingNextPage={isFetchingNextPage}
            hasNextPage={hasNextPage}
            isEmpty={!results.length && !isLoading}
            sx={{
              '& .MuiListItem-root': {
                py: 1,
              },
            }}
            noResultsLabel={
              <HuStateCard
                sx={{ border: 'none' }}
                slotProps={{
                  title: {
                    title: t('no_results_with_filters'),
                  },
                  avatar: {
                    Icon: IconZoomExclamation,
                  },
                }}
              />
            }
          >
            {results.map(user => (
              <HuUserAvatar
                key={user.id}
                user={user}
                profileProps={{ showEmployeeInternalId: true }}
              />
            ))}
          </InfiniteList>
        </Stack>
      </Stack>
    </HuGoThemeProvider>
  );
};

export default NewSeeCollaborators;

type Props = {
  criteria: AudienceCriteria[];
  type?: CriteriaType;
  usersCount: number;
};

export const useCriteriaColaborators = (props?: Props) => {
  const { criteria, type } = props || {};
  const { t } = useLokaliseTranslation('audience');
  const HuGoThemeProvider = useHuGoTheme();

  const title =
    type === CriteriaType.ALL_USERS
      ? t('all_users_title')
      : t('selected_collaborators');

  const { drawer, showDrawer, closeDrawer } = useDrawer(
    () => {
      return (
        <NewSeeCollaborators
          service={(pagination: RequestCursorPagination) =>
            getAudiencesSearch({
              criteria: criteria || [],
              q: pagination.q,
              limit: pagination.limit,
              cursor: pagination.cursor || '',
            })
          }
          queryKey={['audiences-search', criteria]}
        />
      );
    },
    {
      title,
      footer: (
        <HuAlert
          title={t('total_audience', {
            count: props?.usersCount || 0,
          })}
          severity="info"
        />
      ),
      hasBackButton: true,
      secondaryButtonProps: {
        children: t('general:back'),
        onClick: () => closeDrawer(),
        fullWidth: true,
      },
    },
  );
  return {
    drawer: <HuGoThemeProvider>{drawer}</HuGoThemeProvider>,
    showDrawer,
    closeDrawer,
  };
};
