import { useQuery } from 'react-query';
import { useParams } from 'react-router-dom';

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

import HuTitle from '@material-hu/components/design-system/Title';

import { useAuth } from 'src/contexts/JWTContext';
import { getUsersToShare } from 'src/pages/dashboard/performance/services';
import { type ReviewUserToShare } from 'src/pages/dashboard/performance/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import PerformanceLoading from '../../components/PerformanceLoading';
import UserListRow from '../../components/UserList/UserListRow';
import UserListSection from '../../components/UserList/UserListSection';
import { usePerformanceReview } from '../../PerformanceReviewContext';
import { performanceKeys } from '../../queries';

type UserToShareItem = Omit<ReviewUserToShare, 'reviewedFormReviews'>;

const ShareResultsUserList = () => {
  const { t } = useLokaliseTranslation(['performance']);
  const { id } = useParams();
  const { user } = useAuth();
  const { setUserToShareId } = usePerformanceReview();

  const formatFilter = {
    order: 'ASC',
    orderBy: 'SHARE_STATUS',
    page: 1,
    limit: 200,
  };

  const { data, isLoading } = useQuery(
    performanceKeys.usersToShare(id, user?.id, formatFilter),
    () => getUsersToShare(Number(id), user?.id ?? 0, formatFilter),
    {
      select: response => response.data,
      enabled: !!id,
    },
  );

  const users: UserToShareItem[] = data?.items || [];

  if (isLoading) {
    return <PerformanceLoading />;
  }

  return (
    <Stack sx={{ flex: 1, minWidth: 0, width: '100%' }}>
      <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 2, mb: 3 }}>
        <HuTitle
          variant="L"
          title={t('deliver_results')}
        />
      </Stack>

      {users.length > 0 && (
        <UserListSection title={t('types.subordinate_review')}>
          {users.map(item => (
            <UserListRow
              key={item.userId}
              user={{
                id: item.userId,
                profilePicture: item.user?.profilePicture,
                firstName: item.user?.firstName,
                lastName: item.user?.lastName,
              }}
              primary={getFullName(item.user || {})}
              onClick={() => setUserToShareId(item.userId)}
            />
          ))}
        </UserListSection>
      )}
    </Stack>
  );
};

export default ShareResultsUserList;
