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

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

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

import { ACKNOWLEDGEDS_MAX_LENGTH } from 'src/pages/dashboard/acknowledgements/constants';
import { useGetAcknowledged } from 'src/pages/dashboard/acknowledgements/hooks/useGetAcknowledged';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import { acknowledgementFormNames } from '../form';
import { type CreateKudosFormValues } from '../types';

export const SelectAcknowledgedsUsers = () => {
  const { t } = useLokaliseTranslation('acknowledgements');
  const [search, setSearch] = useState('');
  const form = useFormContext<CreateKudosFormValues>();

  const { data: users, isLoading } = useGetAcknowledged(search);

  const selectedUsers = useWatch({
    control: form.control,
    name: 'acknowledgeds',
  });

  const searchUsersOptions: AutocompleteOption[] = useMemo(() => {
    if (!users || isLoading) return [];

    return users.map(user => ({
      label: getFullName(user),
      value: user.id,
    }));
  }, [isLoading, users]);

  const options = useMemo(() => {
    if (search) return searchUsersOptions;

    const filteredSearchUsersOptions = searchUsersOptions.filter(
      user => !selectedUsers.some(selected => selected.value === user.value),
    );

    return [...selectedUsers, ...filteredSearchUsersOptions];
  }, [search, selectedUsers, searchUsersOptions]);

  const maxUsersReached = selectedUsers.length >= ACKNOWLEDGEDS_MAX_LENGTH;

  const helperText = t(
    `recognized_users_max_length${maxUsersReached ? '_limit' : ''}`,
    { count: ACKNOWLEDGEDS_MAX_LENGTH },
  );

  return (
    <FormAutocomplete
      name={acknowledgementFormNames.acknowledgeds}
      options={options}
      autocompleteProps={{
        label: t('recognized_users_label'),
        helperText,
        loading: isLoading,
        placeholder: t('recognized_users_placeholder'),
        multiple: true,
        limitTags: 2,
        onInputChange: (_, value) => setSearch(value),
        getOptionDisabled: option => {
          const isSelected = selectedUsers.some(
            user => user.value === option.value,
          );
          if (!isSelected && maxUsersReached) return true;
          return false;
        },
        renderOption: ({ key, ...props }, option) => {
          return (
            <li
              key={key}
              {...props}
            >
              <Stack
                sx={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  cursor: 'pointer',
                  width: '100%',
                  gap: 2,
                  py: 1,
                  borderRadius: 1,
                }}
              >
                <Checkbox
                  checked={selectedUsers.some(
                    user => user.value === option.value,
                  )}
                />
                <Typography variant="globalM">{option.label}</Typography>
              </Stack>
            </li>
          );
        },
      }}
    />
  );
};
