import { useMemo } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useMutation, useQuery } from 'react-query';
import { useParams } from 'react-router-dom';

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

import HuAvatar from '@material-hu/components/design-system/Avatar';
import HuPills from '@material-hu/components/design-system/Pills';
import useSnackbar from '@material-hu/components/design-system/Snackbar';
import HuTitle from '@material-hu/components/design-system/Title';

import { logEvent } from 'src/config/logging';
import {
  invalidateCycle,
  performanceKeys,
} from 'src/pages/dashboard/performance/queries';
import {
  confirmReception,
  getReviewCycle,
} from 'src/pages/dashboard/performance/services';
import {
  DeliveryStatus,
  ReviewCycleStatus,
  type ReviewDetail,
  type ReviewUser,
} from 'src/pages/dashboard/performance/types';
import { EventName } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName, getInitials } from 'src/utils/userUtils';

import NoReviewText from '../../components/NoReviewText';
import PerformanceLoading from '../../components/PerformanceLoading';
import UserListRow from '../../components/UserList/UserListRow';
import UserListSection from '../../components/UserList/UserListSection';
import { PILL_TYPE } from '../../constants';
import { usePerformanceReview } from '../../PerformanceReviewContext';
import {
  groupReviewsByDirection,
  isDownwardReview,
  isSharedConfirmed,
  type ReviewDirectionGroup,
} from '../../utils';

import ReceivedConfirmation from './ReceivedConfirmation';
import Summary from './Summary/Summary';
import ReviewScoreCardByDirection from './score/ReviewScoreCardByDirection';

type ReviewWithExternalReviewer = ReviewDetail & {
  externalReviewer?: ReviewUser;
};

const MyResultsOverview = () => {
  const { id } = useParams();
  const { t } = useLokaliseTranslation(['performance']);
  const { enqueueSnackbar } = useSnackbar();
  const form = useForm();

  const cycleId = id || '';
  const { setViewingReviewId } = usePerformanceReview();

  const { data: cycle, isLoading: isCycleLoading } = useQuery(
    performanceKeys.cycle(cycleId),
    () => getReviewCycle(cycleId),
    { select: response => response.data },
  );

  const {
    reviewedFormReviews,
    withSummary,
    userTargetUser,
    status: cycleStatus,
    reviewsVisibleAfterFinishedReviewCycle,
    canBeSharedBeforeCycleFinish,
  } = cycle || {};

  const firstReviewedUser = reviewedFormReviews?.[0]?.reviewed;
  const showAllReviews =
    cycleStatus === ReviewCycleStatus.FINISHED ||
    !reviewsVisibleAfterFinishedReviewCycle ||
    canBeSharedBeforeCycleFinish;

  const shareStatus = userTargetUser?.shareStatus;
  const sharedConfirmed = shareStatus === DeliveryStatus.SHARED_CONFIRMED;
  const needConfirmation = shareStatus === DeliveryStatus.SHARED_UNCONFIRMED;

  const { mutate: confirmReceptionMutate, isLoading: isConfirming } =
    useMutation(() => confirmReception(cycleId, userTargetUser?.userId), {
      onSuccess: () => {
        invalidateCycle(cycleId);
        enqueueSnackbar({
          title: t('form.confirm_reception_success'),
          variant: 'success',
        });
      },
    });

  const groups = useMemo<
    ReviewDirectionGroup<ReviewWithExternalReviewer>[]
  >(() => {
    if (!reviewedFormReviews?.length) return [];
    return groupReviewsByDirection(
      reviewedFormReviews as ReviewWithExternalReviewer[],
    );
  }, [reviewedFormReviews]);

  if (!isCycleLoading && reviewedFormReviews?.length === 0) {
    return (
      <NoReviewText
        title={t('admin_check.without_review.title')}
        description={t('admin_check.without_review.description')}
      />
    );
  }

  if (
    !isCycleLoading &&
    (reviewedFormReviews?.length === 0 ||
      (!sharedConfirmed && !needConfirmation))
  ) {
    return (
      <NoReviewText
        title={t('admin_check.not_shared.title')}
        description={t('admin_check.not_shared.description')}
      />
    );
  }

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

  const reviewedFullName =
    getFullName(firstReviewedUser || {}) || t('general:ANONYMOUS');

  if (needConfirmation) {
    return (
      <ReceivedConfirmation
        fullName={reviewedFullName}
        onAccept={() => confirmReceptionMutate()}
        isConfirming={isConfirming}
      />
    );
  }

  return (
    <FormProvider {...form}>
      <Stack sx={{ gap: 3, width: '100%' }}>
        <Paper
          variant="outlined"
          sx={{
            borderRadius: 2,
            p: 3,
            width: '100%',
            boxSizing: 'border-box',
          }}
        >
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              flexWrap: 'wrap',
              gap: 2,
            }}
          >
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 2,
                minWidth: 0,
                flex: 1,
              }}
            >
              <HuAvatar
                size="large"
                src={firstReviewedUser?.profilePicture ?? undefined}
                text={getInitials(reviewedFullName)}
                alt=""
                sx={{ flexShrink: 0 }}
              />
              <HuTitle
                title={reviewedFullName}
                variant="L"
                sx={{ minWidth: 0 }}
              />
            </Stack>
            <Stack sx={{ flexShrink: 0 }}>
              <ReviewScoreCardByDirection
                score={userTargetUser?.score}
                scoreTag={userTargetUser?.scoreTag}
              />
            </Stack>
          </Stack>
        </Paper>

        <Summary
          summary={userTargetUser?.summary}
          withSummary={Boolean(withSummary)}
          shareStatus={shareStatus || DeliveryStatus.NOT_SHARED}
          userId={firstReviewedUser?.userId}
        />

        {!showAllReviews && (
          <NoReviewText
            title={t('admin_check.not_visible_title')}
            description={t('admin_check.not_visible')}
          />
        )}

        {showAllReviews &&
          groups.map(group => (
            <UserListSection
              key={group.titleKey}
              title={t(group.titleKey)}
            >
              {group.reviews.map(review => {
                const reviewer = review.reviewer || review.externalReviewer;
                const reviewerName =
                  getFullName(reviewer || {}) || t('general:ANONYMOUS');
                const isAnswered = review.answered;

                return (
                  <UserListRow
                    key={review.id}
                    user={{
                      id: reviewer?.userId,
                      profilePicture: reviewer?.profilePicture ?? null,
                      firstName: reviewer?.firstName,
                      lastName: reviewer?.lastName,
                      fullName: reviewerName,
                    }}
                    primary={reviewerName}
                    onClick={
                      isAnswered
                        ? () => {
                            setViewingReviewId(review.id);
                            if (
                              shareStatus &&
                              isSharedConfirmed(true, shareStatus) &&
                              isDownwardReview(review.type)
                            ) {
                              logEvent(EventName.PERF_REV_REVIEW_RECEIVED, {
                                cycleId,
                                reviewId: review.id,
                              });
                            }
                          }
                        : undefined
                    }
                  >
                    {isAnswered ? (
                      <ReviewScoreCardByDirection
                        score={review.score}
                        scoreTag={review.scoreTag}
                      />
                    ) : (
                      <HuPills
                        label={t('no_evaluated')}
                        size="small"
                        type={PILL_TYPE.WARNING}
                        hasIcon={false}
                        sx={{ flexShrink: 0, textTransform: 'none' }}
                      />
                    )}
                  </UserListRow>
                );
              })}
            </UserListSection>
          ))}
      </Stack>
    </FormProvider>
  );
};

export default MyResultsOverview;
