import { useState } from 'react';
import { useInfiniteQuery } from 'react-query';
import { useParams } from 'react-router-dom';

import { useDebounce } from '@material-hu/hooks/useDebounce';
import Skeleton from '@material-hu/mui/Skeleton';
import Stack from '@material-hu/mui/Stack';

import { getManagerSurveys } from '../services';
import { SurveyResponse } from '../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormAutocomplete, {
  FormAutocompleteProps,
} from 'src/components/FormInputs/FormAutocomplete';
import InfiniteList from 'src/components/list/InfiniteList';

import { pxKeys } from '../queries';

type SurveysAutocompleteProps = {
  name: string;
  loading?: boolean;
} & FormAutocompleteProps;

const SurveysAutocomplete = ({
  name,
  loading,
  ...rest
}: SurveysAutocompleteProps) => {
  const [query, setQuery] = useState('');
  const debouncedQuery = useDebounce(query);
  const { t } = useLokaliseTranslation('people_experience');
  const urlParams = useParams();
  const surveyId = urlParams.id;

  const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } =
    useInfiniteQuery(
      pxKeys.collaboratorSurveysList({
        q: debouncedQuery,
      }),
      ({ pageParam = 0 }) =>
        getManagerSurveys({
          status: undefined,
          q: debouncedQuery,
          limit: 10,
          page: pageParam,
        }),
      {
        getNextPageParam: lastPage =>
          lastPage.data.page === lastPage.data.totalPages
            ? undefined
            : lastPage.data.page,
      },
    );

  const surveys =
    data?.pages
      ?.flatMap(page => page.data.items)
      .map(survey => ({
        id: survey.id,
        title: survey.name,
      })) || [];

  return (
    <FormAutocomplete
      name={name}
      hideCheckbox
      limitTags={1}
      options={surveys.filter(survey => Number(survey.id) !== Number(surveyId))}
      isOptionEqualToValue={(option: SurveyResponse, value: number) =>
        option?.id === value
      }
      getOptionLabel={option => option.title}
      textFieldProps={{
        label: t('COMPARE_WITH'),
        sx: {
          '.MuiInputBase-root': {
            bgcolor: theme => theme.palette.new.background.elements.default,
          },
        },
      }}
      {...rest}
      loading={isLoading}
      query={(value: string) => {
        setQuery(value);
      }}
      infinite={
        <InfiniteList
          isSuccess={!!data}
          isLoading={isLoading}
          isEmpty={data?.pages && !data?.pages[0]?.data?.count}
          fetchNextPage={fetchNextPage}
          hasNextPage={hasNextPage}
          isFetchingNextPage={isFetchingNextPage}
          renderSkeleton={
            <Stack
              direction="row"
              alignItems="center"
              px={2}
              py={1}
            >
              <Skeleton
                animation="wave"
                height={25}
                width={18}
                style={{ borderRadius: 1, marginLeft: 12, marginRight: 18 }}
              />
              <Skeleton
                animation="wave"
                height={22}
                style={{ borderRadius: 2 }}
                width="100%"
              />
            </Stack>
          }
        >
          <div />
        </InfiniteList>
      }
    />
  );
};

export default SurveysAutocomplete;
