import { FC, Fragment } from 'react';
import { useFormContext } from 'react-hook-form';
import { useInfiniteQuery } from 'react-query';
import { useSearchParams } from 'react-router-dom';

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

import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuList from '@material-hu/components/design-system/List';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';
import HuRadioButton from '@material-hu/components/design-system/RadioButton/RadioButton';
import HuTitle from '@material-hu/components/design-system/Title';

import useGeneralError from 'src/hooks/useGeneralError';
import { getDraftPermissions } from 'src/services/posts';
import { DraftPermission } from 'src/types/posts';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { flatPages } from 'src/utils/pagination';
import { getFullName, getInitials } from 'src/utils/userUtils';

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

import { NewPostDraftSteps } from '../../constants';
import { postDraftKeys } from '../../queries';
import ListSkeleton from '../skeleton/ListSkeleton';

const LIMIT = 10;

const FinalAuthor: FC = () => {
  const { t } = useLokaliseTranslation(['communication']);
  const showGeneralError = useGeneralError();
  const { watch, setValue } = useFormContext();
  const [searchParams, setSearchParams] = useSearchParams();

  const {
    data: draftPermissionsInfinite,
    isLoading,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useInfiniteQuery(
    postDraftKeys.all({ limit: LIMIT }),
    ({ pageParam = '' }) =>
      getDraftPermissions({
        limit: LIMIT,
        cursor: pageParam,
        type: 'FOR_CREATION',
      }),
    {
      getNextPageParam: lastPage => lastPage?.data?.cursor,
      onError: err => {
        showGeneralError(err, t('error_loading_draft_permissions'));
      },
    },
  );

  const draftPermissions = flatPages(draftPermissionsInfinite);

  const handleChange = (draftPermission: DraftPermission) => {
    setValue('permissionId', draftPermission.id);
    setValue('authorFullName', getFullName(draftPermission.userTo));
    setValue('authorProfilePicture', draftPermission.userTo.profilePicture);
    setSearchParams({
      ...Object.fromEntries(searchParams.entries()),
      permissionId: draftPermission.id.toString(),
    });
  };

  return (
    <Stack sx={{ gap: 3 }}>
      <HuTitle
        title={t('drafts_for_review.title_final_author')}
        variant="S"
        description={t('drafts_for_review.description', {
          context: NewPostDraftSteps.FINAL_AUTHOR,
        })}
        sx={{ gap: 2 }}
      />
      <HuCardContainer fullWidth>
        <HuList>
          <InfiniteList
            isSuccess={!!draftPermissions}
            isLoading={isLoading}
            fetchNextPage={fetchNextPage}
            hasNextPage={hasNextPage}
            isFetchingNextPage={isFetchingNextPage}
            customLoader={<ListSkeleton />}
            renderSkeleton={
              <Stack sx={{ ml: 2 }}>
                <HuListItem loading />
                <HuListItem loading />
                <HuListItem loading />
              </Stack>
            }
          >
            {draftPermissions?.map((draftPermission, index) => (
              <Fragment key={draftPermission?.id}>
                <HuRadioButton
                  label={getFullName(draftPermission?.userTo)}
                  description={draftPermission?.userTo?.email ?? undefined}
                  avatarProps={{
                    src: draftPermission?.userTo?.profilePicture ?? undefined,
                    text: getInitials(getFullName(draftPermission?.userTo)),
                  }}
                  onClick={() => handleChange(draftPermission)}
                  isActive={watch('permissionId') === draftPermission?.id}
                />
                {index !== draftPermissions.length - 1 && (
                  <Divider sx={{ my: 1.5 }} />
                )}
              </Fragment>
            ))}
          </InfiniteList>
        </HuList>
      </HuCardContainer>
    </Stack>
  );
};

export default FinalAuthor;
