import { useCallback, useMemo, useState } from 'react';

import isNil from 'lodash-es/isNil';
import Stack from '@material-hu/mui/Stack';

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

import { useAuth } from 'src/contexts/JWTContext';
import {
  type DeliveryStatus,
  type ReviewUserToShare,
} from 'src/pages/dashboard/performance/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { getIsReviewShared } from '../../../utils';

import SummaryEditor from './components/SummaryEditor';
import SummaryReadOnly from './components/SummaryReadOnly';
import {
  getPlainTextFromHtml,
  getSummaryView,
  SUMMARY_PREVIEW_MAX_LENGTH,
} from './utils';

type SummaryProps = Partial<Pick<ReviewUserToShare, 'userId' | 'summary'>> & {
  withSummary: boolean;
  shareStatus: DeliveryStatus;
  saveSummary?: () => void;
  isSavingSummary?: boolean;
  isEditing?: boolean;
  onEdit?: () => void;
};

const Summary = (props: SummaryProps) => {
  const {
    summary,
    shareStatus,
    saveSummary,
    userId,
    withSummary,
    isSavingSummary,
    isEditing = false,
    onEdit,
  } = props;
  const [showMore, setShowMore] = useState(false);

  const { t } = useLokaliseTranslation('performance');
  const { user: currentUser } = useAuth();

  const plainTextSummary = useMemo(
    () => getPlainTextFromHtml(summary),
    [summary],
  );
  const shouldShowMoreButton =
    plainTextSummary.length > SUMMARY_PREVIEW_MAX_LENGTH;
  const hasSummary = plainTextSummary.trim().length > 0;
  const isCurrentUserReviewSubject =
    !isNil(userId) && !isNil(currentUser?.id) && userId === currentUser.id;
  const isReviewShared = getIsReviewShared(shareStatus);
  const summaryView = useMemo(
    () =>
      getSummaryView({
        withSummary,
        isCurrentUserReviewSubject,
        isReviewShared,
        summary,
        hasSummary,
        isEditing,
        hasSaveSummaryAction: Boolean(saveSummary),
      }),
    [
      withSummary,
      isCurrentUserReviewSubject,
      isReviewShared,
      summary,
      hasSummary,
      isEditing,
      saveSummary,
    ],
  );

  const handleToggleShowMore = useCallback(
    () => setShowMore(prev => !prev),
    [],
  );
  const handleEdit = useCallback(() => onEdit?.(), [onEdit]);

  if (!summaryView.shouldRenderCard) {
    return null;
  }

  return (
    <CardContainer
      fullWidth
      padding={24}
    >
      <Stack sx={{ gap: 2 }}>
        <Title
          variant="S"
          title={t('summary.title')}
          description={
            summaryView.showEditor ? t('summary.description') : undefined
          }
        />
        {summaryView.showReadOnly && (
          <SummaryReadOnly
            summaryHtml={summary || ''}
            plainTextSummary={plainTextSummary}
            shouldShowMoreButton={shouldShowMoreButton}
            showMore={showMore}
            onToggleShowMore={handleToggleShowMore}
            showEditButton={summaryView.showEditButton}
            onEdit={handleEdit}
            seeToggleLabel={t('see', {
              context: showMore ? 'less' : 'more',
            })}
            editLabel={t('general:edit')}
          />
        )}
        {summaryView.showEditor && (
          <SummaryEditor
            userId={userId}
            summary={summary}
            saveSummary={saveSummary}
            isSavingSummary={isSavingSummary}
            placeholder={t('summary.placeholder')}
            saveLabel={t('general:save')}
          />
        )}
      </Stack>
    </CardContainer>
  );
};

export default Summary;
