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

import {
  GetDrawerConfiguration,
  useDrawerV2,
} from '@material-hu/hooks/useDrawerV2';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import * as animations from '@material-hu/utils/animations';

import HuAlert from '@material-hu/components/design-system/Alert';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
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 { getSelectedCollaborators } from '../../../utils';

import FilterListItem from './FilterListItem';
import { getCollaboratorsSelectedDrawer } from './getCollaboratorsSelectedDrawer';

type CollaboratorsDrawerProps = {
  collaborators: JourneyAssignee[];
};

export const getCollaboratorsFilterDrawer: GetDrawerConfiguration<
  CollaboratorsDrawerProps
> = ({ collaborators, closeDrawer }) => {
  const { t } = useLokaliseTranslation(['employee_lifecycle', 'audience']);
  const { palette } = useTheme();

  const [search, setSearch] = useState('');
  const { setQueryStates, filterParams } = useFilterParams();

  const [selectedCollaborators, setSelectedCollaborators] = useState<
    JourneyAssignee[]
  >([]);

  useEffect(() => {
    // Used to sync the queryIds with the selection
    setSelectedCollaborators(
      getSelectedCollaborators(collaborators, filterParams.collaborators),
    );
  }, [collaborators, filterParams.collaborators]);

  // Drawer to show the selected collaborators
  const selectedCollaboratorsDrawer = useDrawerV2(
    getCollaboratorsSelectedDrawer,
  );

  const handleOpenSelectedCollaboratorsDrawer = () =>
    selectedCollaboratorsDrawer.showDrawer({
      selectedCollaborators,
      setSelectedCollaborators,
    });

  const filteredCollaborators = useMemo(() => {
    if (!collaborators) return [];

    return collaborators?.filter(user =>
      user.fullName.toLowerCase().includes(search.toLowerCase()),
    );
  }, [collaborators, search]);

  const handleApplyFilter = () => {
    const collaboratorsToString = selectedCollaborators
      .map(collaborator => collaborator.id)
      .join(',');

    setQueryStates({ collaborators: collaboratorsToString });
    closeDrawer();
  };

  const handleClearFilter = () => {
    setSelectedCollaborators([]);
    setQueryStates({ collaborators: null, limit: null });
    closeDrawer();
  };

  const handleSelectCollaborator = (collaborator: JourneyAssignee) => {
    setSelectedCollaborators(
      addOrRemoveById(selectedCollaborators, collaborator),
    );
  };

  const selectionsIds = new Set(
    selectedCollaborators?.map(collaborator => collaborator.id),
  );

  return {
    title: t(
      'employee_lifecycle:tasks.tasks_module.task_assignees_dialog_title',
    ),
    children: (
      <>
        <Stack sx={{ height: '100%', justifyContent: 'space-between' }}>
          <HuCardContainer
            fullWidth
            color="grey"
          >
            <HuSearch
              value={search}
              onChange={setSearch}
            />
            <Stack
              sx={{
                mt: 2,
                borderRadius: 2,
                maxHeight: 'calc(100vh - 470px)',
                overflowY: 'auto',
                backgroundColor: palette.new.background.elements.default,
              }}
            >
              {filteredCollaborators?.map((collaborator, index) => {
                return (
                  <Fragment key={collaborator.id}>
                    <FilterListItem
                      collaborator={collaborator}
                      onSelect={handleSelectCollaborator}
                      selected={selectionsIds.has(collaborator.id)}
                    />
                    {index !== filteredCollaborators.length - 1 && (
                      <Divider sx={{ mx: 1 }} />
                    )}
                  </Fragment>
                );
              })}
            </Stack>
          </HuCardContainer>

          <Stack sx={{ gap: 1.5 }}>
            <HuAlert
              severity="warning"
              title={t(
                'employee_lifecycle:tasks.tasks_module.task_assignees_dialog_warning',
              )}
            />
            {selectionsIds.size > 0 && (
              <HuAlert
                sx={{
                  animation: `${animations.fadeIn} 0.3s ease-in-out backwards`,
                }}
                severity="info"
                title={t('audience:form_employees_selector.user_reach', {
                  count: selectionsIds.size,
                })}
                action={{
                  text: t('audience:form_employees_selector.see_user_reach'),
                  onClick: handleOpenSelectedCollaboratorsDrawer,
                }}
              />
            )}
          </Stack>
        </Stack>
        {selectedCollaboratorsDrawer.drawer}
      </>
    ),
    primaryButtonProps: {
      children: t('general:apply'),
      fullWidth: true,
      onClick: handleApplyFilter,
      disabled: !selectionsIds.size,
    },
    secondaryButtonProps: {
      children: t('general:clean_selection'),
      fullWidth: true,
      onClick: handleClearFilter,
    },
    onClose: closeDrawer,
  };
};
