import { useEffect, useMemo, useState } from 'react';

import { GetDrawerConfiguration } from '@material-hu/hooks/useDrawerV2';
import Stack from '@material-hu/mui/Stack';

import HuSearch from '@material-hu/components/design-system/Inputs/Search';

import { addOrRemoveById } from 'src/utils/arrays';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useFilterParams } from '../../../hooks/useFilterParams';
import { JourneyAssignee } from '../../../types/task';

import FilterListItem from './FilterListItem';

type Props = {
  selectedCollaborators: JourneyAssignee[];
  setSelectedCollaborators: (collaborators: JourneyAssignee[]) => void;
};

export const getCollaboratorsSelectedDrawer: GetDrawerConfiguration<Props> = ({
  closeDrawer,
  selectedCollaborators,
  setSelectedCollaborators,
}) => {
  const { t } = useLokaliseTranslation('audience');
  const { setQueryStates } = useFilterParams();
  const [search, setSearch] = useState('');
  const [selection, setSelection] = useState<JourneyAssignee[]>([]);

  useEffect(() => {
    // Used to sync the queryIds with the selection
    setSelection(selectedCollaborators);
  }, [selectedCollaborators]);

  // Filter the selected collaborators based on search
  const filteredSelectedCollaborators = useMemo(() => {
    if (!selection) return [];

    return selection.filter(item =>
      item.fullName.toLowerCase().includes(search.toLowerCase()),
    );
  }, [selection, search]);

  const handleDeselectCollaborator = (collaborator: JourneyAssignee) => {
    const newSelectedItems = addOrRemoveById(selection, collaborator);
    setSelection(newSelectedItems);

    if (search) setSearch('');

    // If there are no more collaborators selected
    // we clear the search and the query states and close the drawer
    if (!newSelectedItems.length) {
      setQueryStates({ collaborators: null, limit: null });
      setSelectedCollaborators([]);
      closeDrawer();
    }
  };

  const onCloseDrawer = () => {
    setSelectedCollaborators(selection);
    closeDrawer();
  };

  return {
    title: t('form_employees_selector.selected_users'),
    hasBackButton: true,
    onClose: onCloseDrawer,
    children: (
      <Stack>
        <HuSearch
          value={search}
          onChange={setSearch}
          sx={{ mb: 2 }}
        />
        {filteredSelectedCollaborators.map(collaborator => (
          <FilterListItem
            key={collaborator.id}
            collaborator={collaborator}
            onSelect={handleDeselectCollaborator}
            isReadOnly
          />
        ))}
      </Stack>
    ),
    primaryButtonProps: {
      children: t('general:close'),
      fullWidth: true,
      onClick: onCloseDrawer,
    },
  };
};
