/**
 * @Move (SQPM)
 * Only used by the Performance module - move to Performance/
 */
import { Fragment, useEffect, useState } from 'react';
import { useFormContext } from 'react-hook-form';
import { useInfiniteQuery } from 'react-query';

import { isNil } from 'lodash-es';
import ListItem from '@material-hu/mui/ListItem';
import ListItemText from '@material-hu/mui/ListItemText';
import Skeleton from '@material-hu/mui/Skeleton';
import Stack from '@material-hu/mui/Stack';

import { reviewsKeys } from 'src/pages/dashboard/Performance/queries';
import * as performanceService from 'src/services/performanceService';
import {
  ReviewQuestionOrigin,
  type ReviewTemplate,
  SpecialQuestionType,
} from 'src/types/performance';
import { flatPages } from 'src/utils/tableUtils';

import FormAutocomplete, {
  type Props as FormAutocompleteProps,
} from '../FormInputs/FormAutocomplete';
import { InfiniteList } from '../InfiniteList';

import SpecialTemplateChip from './SpecialTemplateChip';

type Props = {
  name: string;
  loading?: boolean;
  isOptionEqualToValue?: (
    option: ReviewTemplate,
    value: ReviewTemplate,
  ) => boolean;
  disabled?: boolean;
} & FormAutocompleteProps;

function TemplatesAutocomplete({
  name,
  loading,
  isOptionEqualToValue,
  disabled,
  ...rest
}: Props) {
  const [query, setQuery] = useState('');
  const { setValue, getValues } = useFormContext();

  const formatFilter = {
    page: 0,
    limit: 100,
    origin: ReviewQuestionOrigin.PERFORMANCE_REVIEW,
  };

  const {
    data: infiniteTemplates,
    isLoading: infiniteTemplatesLoading,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useInfiniteQuery(
    reviewsKeys.templates(formatFilter),
    ({ pageParam = 0 }) =>
      performanceService.getReviewsTemplates({
        ...formatFilter,
        search: query,
        limit: 10,
        page: pageParam,
      }),
    {
      getNextPageParam: lastPage =>
        lastPage.data.page === lastPage.data.totalPages
          ? undefined
          : lastPage.data.page,
    },
  );

  const templates = flatPages(infiniteTemplates);

  const infinite = (
    <InfiniteList
      isSuccess={!!infiniteTemplates}
      isLoading={infiniteTemplatesLoading}
      isEmpty={
        infiniteTemplates?.pages &&
        !infiniteTemplates?.pages[formatFilter.page]?.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>
  );

  const optionEquality =
    isOptionEqualToValue || ((option, value) => option?.id === value?.id);

  useEffect(() => {
    const value = getValues(name);
    if (value?.id) {
      const found = templates.find(t => t.id === value.id);
      if (
        found &&
        found !== value &&
        JSON.stringify(found) !== JSON.stringify(value)
      ) {
        setValue(name, found, { shouldDirty: false });
      }
    }
  }, [templates, name, getValues, setValue]);

  return (
    <FormAutocomplete
      name={name}
      hideCheckbox
      autocompleteProps={{
        limitTags: 1,
        options: templates,
        isOptionEqualToValue: optionEquality,
        getOptionLabel: (rt: ReviewTemplate) => rt.title,
        disabled,
        renderOption: (renderProps, option: ReviewTemplate, { index }) => (
          <Fragment key={option.id}>
            <ListItem
              {...renderProps}
              secondaryAction={
                <Stack sx={{ gap: 1, flexDirection: 'row' }}>
                  {!!option?.goalsProgressMode && (
                    <SpecialTemplateChip type={SpecialQuestionType.GOAL} />
                  )}
                  {!isNil(option.competenciesQuestionTemplateId) && (
                    <SpecialTemplateChip
                      type={SpecialQuestionType.COMPETENCIES}
                    />
                  )}
                </Stack>
              }
            >
              <ListItemText
                primary={option.title}
                primaryTypographyProps={{
                  color: 'textPrimary',
                  noWrap: true,
                }}
              />
            </ListItem>
            {index === templates.length - 1 && infinite}
          </Fragment>
        ),
      }}
      {...rest}
      loading={infiniteTemplatesLoading}
      query={setQuery}
      sx={{
        width: '100%',
        '& .MuiTextField-root': {
          width: '100%',
        },
        '& .MuiInputBase-root': {
          borderTopRightRadius: 0,
          borderBottomRightRadius: 0,
        },
      }}
    />
  );
}

export default TemplatesAutocomplete;
