import { FC, useState } from 'react';
import { useForm, FormProvider } from 'react-hook-form';

import { AxiosResponse } from 'axios';

import Stack from '@material-hu/mui/Stack';

import SearchIcon from 'src/icons/Search';
import { User, UserListResponse } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { peopleSearchKeys } from 'src/components/dashboard/people/queries';
import { FormTextField } from 'src/components/FormInputs';

import { PeopleList } from './PeopleList';

export type PeopleSearchProps = {
  queryKey?: (
    search: string,
    filterSelf?: boolean,
    notIncludingIds?: number[],
  ) => any[];
  getUsersList?: (
    search: string,
    page: number,
    limit: number,
  ) => Promise<AxiosResponse<UserListResponse>>;
  onSelect?: (user: User) => any;
  limit?: number;
  inputContainerStyle?: {};
  listContainerStyle?: {};
  select?: (users: User[]) => User[];
  multiple?: boolean;
  filterSelf?: boolean;
  notIncludingIds?: number[];
  keepPreviousData?: boolean;
  isPeopleModule?: boolean;
};

export const PeopleSearch: FC<PeopleSearchProps> = props => {
  const {
    queryKey = peopleSearchKeys.detail,
    getUsersList,
    onSelect,
    limit = 100,
    inputContainerStyle = {},
    listContainerStyle = {},
    select = (users: User[]) => users,
    multiple = false,
    filterSelf = false,
    notIncludingIds = [],
    keepPreviousData = false,
  } = props;

  const [checks, setChecks] = useState<number[]>([]);

  const { t } = useLokaliseTranslation('people');

  const form = useForm({
    defaultValues: {
      query: '',
    },
  });

  const { watch } = form;

  const query = watch('query');

  const handleCheck = (id: number) => {
    const newChecks = [...checks];
    const index = checks.indexOf(id);

    if (index === -1) {
      newChecks.push(id);
    } else {
      newChecks.splice(index, 1);
    }

    setChecks(newChecks);
  };

  const handleSelect = (user: User) => {
    if (multiple) {
      handleCheck(user.id);
    }

    onSelect && onSelect(user);
  };

  return (
    <>
      <Stack
        sx={{
          alignItems: 'center',
          flexDirection: 'row',
          backgroundColor: 'background.default',
          borderRadius: 22,
          display: 'flex',
          height: 44,
          px: 2,
          m: 1,
          ...inputContainerStyle,
        }}
      >
        <SearchIcon
          color="action"
          fontSize="small"
        />
        <Stack
          sx={{
            flexGrow: 1,
            m: 2,
          }}
        >
          <FormProvider {...form}>
            <form noValidate>
              <FormTextField
                name="query"
                ariaLabel={t('SEARCH_CONTACTS')}
                placeholder={t('SEARCH_CONTACTS')}
                fullWidth
                sx={{
                  '& fieldset': {
                    borderColor: 'transparent !important',
                  },
                }}
              />
            </form>
          </FormProvider>
        </Stack>
      </Stack>
      <PeopleList
        queryKey={queryKey}
        limit={limit}
        listContainerStyle={listContainerStyle}
        select={select}
        multiple={multiple}
        query={query}
        handleSelect={handleSelect}
        checks={checks}
        filterSelf={filterSelf}
        notIncludingIds={notIncludingIds}
        keepPreviousData={keepPreviousData}
        getUsersList={getUsersList}
      />
    </>
  );
};

export default PeopleSearch;
