import { useMemo, useState } from 'react';
import { useFormContext } from 'react-hook-form';
import { useQuery } from 'react-query';

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

import FormAutocomplete from '@material-hu/components/design-system/Inputs/Autocomplete/form';
import { type AutocompleteOption } from '@material-hu/components/design-system/Inputs/Autocomplete/types';

import { getExternalUserReviewers } from 'src/pages/dashboard/performance/services';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

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

type ExternalUserReviewersAutocompleteProps = {
  name: string;
  loading?: boolean;
  setIsNewExternal?: (value: boolean) => void;
};

const ExternalUserReviewersAutocomplete = ({
  name,
  loading,
  setIsNewExternal,
}: ExternalUserReviewersAutocompleteProps) => {
  const { t } = useLokaliseTranslation('performance');
  const [search, setSearch] = useState('');

  const { setValue } = useFormContext();

  const debouncedSearch = useDebounce(search);

  const params = {
    q: debouncedSearch || undefined,
    page: 0,
    limit: 20,
  };

  const { data, isLoading } = useQuery(
    performanceKeys.externalUserReviewers(params),
    () => getExternalUserReviewers(params),
    {
      select: r => r.data,
    },
  );

  const options = useMemo<AutocompleteOption[]>(
    () =>
      data?.items.map(reviewer => ({
        value: reviewer.id,
        label: getFullName(reviewer),
        description: reviewer.email,
      })) ?? [],
    [data],
  );

  const handleCreate = (inputValue: string) => {
    setIsNewExternal?.(true);
    const index = inputValue.indexOf(' ');
    setValue(
      'firstName',
      index !== -1 ? inputValue.substring(0, index) : inputValue,
    );
    setValue('lastName', index !== -1 ? inputValue.substring(index + 1) : '');
  };

  return (
    <FormAutocomplete
      name={name}
      options={options}
      autocompleteProps={{
        placeholder: t('nominate_reviewers.search_name'),
        loading: loading || isLoading,
        multiple: false,
        isServerFiltered: true,
        onInputChange: (_event, value) => setSearch(value),
        onCreate: handleCreate,
      }}
    />
  );
};

export default ExternalUserReviewersAutocomplete;
