/**
 * @deprecated Use `IndividualSelection` from
 * `@material-hu/components/composed-components/audience/IndividualSelection` (also has `form.tsx` variant).
 *
 * Migration notes:
 * - Props `{ onRemove, processId }` are EmployeeLifecycle-specific — Hugo's `IndividualSelection`
 *   likely accepts a service/query prop instead of a hardcoded `processId`. Verify its API before migrating.
 * - Data-fetching (`getAssignmentAudienceUsers`) is embedded locally — confirm Hugo version accepts it as a prop.
 * - Internal `InfiniteList` dependency goes away with migration.
 */
import { useForm, FormProvider } from 'react-hook-form';
import { useInfiniteQuery } from 'react-query';

import { useDebounce } from '@material-hu/hooks/useDebounce';
import { IconZoomExclamation } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import HuStateCard from '@material-hu/components/composed-components/StateCard';
import HuFormSearch from '@material-hu/components/design-system/Inputs/Search/form';
import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import { employeeLifecycleKeys } from 'src/pages/dashboard/EmployeeLifecycle/queries';
import {
  AssignmentAudienceUser,
  getAssignmentAudienceUsers,
} from 'src/pages/dashboard/EmployeeLifecycle/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { InfiniteList } from 'src/components/InfiniteList';

import UserListItem from './components/UserListItem';

const AudienceUsersList = ({
  onRemove,
  processId,
}: {
  onRemove: (userId: number) => void;
  processId: string;
}) => {
  const { t } = useLokaliseTranslation('audience');

  const form = useForm<{ search: string }>({
    defaultValues: {
      search: '',
    },
  });

  const search = form.watch('search');

  const debouncedSearch = useDebounce(search);

  const selectedUsersQuery = useInfiniteQuery<AssignmentAudienceUser[]>(
    employeeLifecycleKeys.audience({ processId, search: debouncedSearch }),
    ({ pageParam = 0 }) =>
      getAssignmentAudienceUsers({
        processId: processId,
        page: pageParam,
        limit: 10,
        search: debouncedSearch,
      }),
    {
      enabled: !!processId,
      getNextPageParam: (lastPage, allPages) => {
        const allItemsLength = allPages.flat().length;

        return lastPage.length ? allItemsLength : undefined;
      },
      keepPreviousData: true,
    },
  );

  const allUsers = selectedUsersQuery?.data?.pages?.flat() || [];

  if (selectedUsersQuery.isLoading) {
    return <HuCircularProgress centered />;
  }

  return (
    <FormProvider {...form}>
      <Stack sx={{ gap: 1 }}>
        <HuFormSearch
          name="search"
          inputProps={{
            disabled: !search && !allUsers?.length,
          }}
        />
        {!allUsers?.length && (
          <HuStateCard
            Icon={IconZoomExclamation}
            title={t('form_employees_selector.no_search_results_title')}
            description={t(
              'form_employees_selector.no_search_results_description',
            )}
            sx={{ border: 'none' }}
          />
        )}

        <InfiniteList
          isEmpty={!allUsers?.length}
          isSuccess={!!selectedUsersQuery.isSuccess}
          isLoading={selectedUsersQuery.isLoading}
          fetchNextPage={selectedUsersQuery.fetchNextPage}
          isFetchingNextPage={selectedUsersQuery.isFetchingNextPage}
          hasNextPage={!!selectedUsersQuery.hasNextPage}
          sx={{ flex: 1 }}
          noResultsLabel={
            <HuStateCard
              sx={{ border: 'none' }}
              Icon={IconZoomExclamation}
              title={t('form_employees_selector:no_search_results_title')}
              description={t(
                'form_employees_selector:no_search_results_description',
              )}
            />
          }
        >
          {allUsers?.map(user => (
            <UserListItem
              key={user.id}
              id={user.id}
              onRemove={onRemove}
              slotProps={{
                title: {
                  title:
                    user.fullName || [user.firstName, user.lastName].join(' '),
                },
                avatar: user.avatar?.url
                  ? {
                      src: user.avatar.url,
                    }
                  : {},
              }}
              sx={{ flex: 0 }}
            />
          ))}
        </InfiniteList>
      </Stack>
    </FormProvider>
  );
};

export default AudienceUsersList;
