import { useState } from 'react';
import { type UseQueryResult } from 'react-query';

import { type AutocompleteRenderOptionState } from '@material-hu/mui/Autocomplete';
import Avatar from '@material-hu/mui/Avatar';
import Checkbox from '@material-hu/mui/Checkbox';
import { useTheme } from '@material-hu/mui/index';
import ListItem, { type ListItemProps } from '@material-hu/mui/ListItem';
import ListItemAvatar from '@material-hu/mui/ListItemAvatar';
import ListItemText from '@material-hu/mui/ListItemText';
import { createFilterOptions } from '@material-hu/mui/useAutocomplete';

import { useGetUserList } from 'src/hooks/queryHooks/formUserAutocomplete';
import { type User } from 'src/types/user';
import { getFullName } from 'src/utils/userUtils';

import {
  FormAutocomplete,
  type FormAutocompleteProps,
} from './FormAutocomplete';

export type FormUserAutocompleteProps = FormAutocompleteProps & {
  needSubordinates?: boolean;
  needAcknowledgeds?: boolean;
  usersQuery?: (search: string) => UseQueryResult;
  getOptionDisabled?: (option: User) => boolean;
};

/**
 * @deprecated This component does not implement Hugo's design system.
 */
export const FormUserAutocompleteItem = (
  multiple: boolean,
  withAvatar: boolean = true,
) =>
  function FormUserAutocompleteItemComponent(
    props: ListItemProps,
    option: User,
    state: AutocompleteRenderOptionState & { disabled?: boolean },
  ) {
    const theme = useTheme();
    const { id, profilePicture } = option;

    return (
      <ListItem
        {...props}
        key={id}
      >
        {multiple && <Checkbox checked={state.selected} />}
        {withAvatar && (
          <ListItemAvatar>
            <Avatar
              src={profilePicture ?? undefined}
              sx={{
                height: 32,
                width: 32,
              }}
            />
          </ListItemAvatar>
        )}
        <ListItemText
          primary={getFullName(option)}
          primaryTypographyProps={{
            color: state.disabled
              ? theme.palette.new.text.neutral.disabled
              : theme.palette.new.text.neutral.default,
            noWrap: true,
            variant: 'body1',
          }}
          sx={{ py: 0.5 }}
        />
      </ListItem>
    );
  };

export const FormUserAutocomplete = (props: FormUserAutocompleteProps) => {
  const {
    multiple = false,
    needSubordinates = false,
    needAcknowledgeds = false,
    StartAdornmentCustom,
    usersQuery,
    getOptionDisabled,
    ...autocompleteProps
  } = props;
  const [search, setSearch] = useState('');

  const { data, isLoading } =
    usersQuery?.(search) ||
    useGetUserList(search, needSubordinates, needAcknowledgeds);

  const filterOptions = createFilterOptions({
    stringify: (user: User) =>
      `${getFullName(user)} ${user.employeeInternalId}`,
  });

  return (
    <FormAutocomplete
      limitTags={2}
      filterOptions={filterOptions}
      getOptionLabel={(user: User) => getFullName(user)}
      isOptionEqualToValue={(option: any, value: any) => option.id === value.id}
      renderOption={FormUserAutocompleteItem(multiple)}
      onInputChange={(_, value) => setSearch(value)}
      options={data || []}
      loading={isLoading}
      multiple={multiple}
      StartAdornmentCustom={StartAdornmentCustom}
      getOptionDisabled={getOptionDisabled}
      {...autocompleteProps}
    />
  );
};

export default FormUserAutocomplete;
