import { useMemo, useState } from 'react';

import { IconEdit } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

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

import useFormatDate from 'src/hooks/useFormatDate';
import {
  type DeliveryStatus,
  type ReviewUser,
} from 'src/pages/dashboard/performance/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import RichText from '../../components/RichText';

import ReviewHeaderCard from './ReviewHeaderCard';
import ReviewScoreCardByDirection from './score/ReviewScoreCardByDirection';

type CompletedReviewCardProps = {
  reviewed?: ReviewUser;
  score?: number | null;
  scoreTag?: string | null;
  answeredAt?: string;
  summary?: string;
  withSummary: boolean;
  shareStatus: DeliveryStatus;
  showSharedMessage: boolean;
  canRequestEdition: boolean;
  onRequestEdition: () => void;
};

const MAX_LENGTH = 290;

const CompletedReviewCard = ({
  reviewed,
  score,
  scoreTag,
  answeredAt,
  summary,
  withSummary,
  shareStatus,
  showSharedMessage,
  canRequestEdition,
  onRequestEdition,
}: CompletedReviewCardProps) => {
  const { t } = useLokaliseTranslation(['performance']);
  const { formatDate } = useFormatDate();
  const [showMore, setShowMore] = useState(false);

  const parsedText = useMemo(() => {
    const parser = new DOMParser();
    const doc = parser.parseFromString(summary || '', 'text/html');
    return doc.body.textContent || '';
  }, [summary]);

  const shouldShowMoreButton = parsedText.length > MAX_LENGTH;
  const hasSummary = parsedText.trim().length > 0;
  const showSummary = withSummary && hasSummary;

  const formattedDate = answeredAt ? formatDate(answeredAt, 'dd/MMM/yy') : '--';
  const formattedDateWithUppercaseMonth = formattedDate.toUpperCase();
  const evaluationDateText = t('form.review.evaluation_date', {
    date: formattedDateWithUppercaseMonth,
  });
  const footer = canRequestEdition
    ? {
        action1: {
          title: t('form.request_edit.title'),
          onClick: onRequestEdition,
          endIcon: <IconEdit />,
        },
        text: showSharedMessage
          ? t(`form.share_review.shared_review_${shareStatus}`)
          : undefined,
      }
    : undefined;

  return (
    <ReviewHeaderCard
      user={reviewed}
      subtitle={evaluationDateText}
      footer={footer}
      rightSlot={
        <ReviewScoreCardByDirection
          score={score}
          scoreTag={scoreTag}
          size="large"
        />
      }
    >
      {showSummary && (
        <Stack sx={{ gap: 1 }}>
          <HuTitle
            variant="S"
            title={t('summary.title')}
          />
          <RichText
            text={
              !shouldShowMoreButton || showMore
                ? summary || ''
                : `<p>${parsedText.slice(0, MAX_LENGTH)}...</p>`
            }
            sx={{ mb: 0 }}
          />
          {shouldShowMoreButton && (
            <Stack sx={{ alignItems: 'flex-end' }}>
              <Button
                variant="text"
                onClick={() => setShowMore(prev => !prev)}
                sx={{ minWidth: 40, maxWidth: 100, height: 10 }}
              >
                {t('see', { context: showMore ? 'less' : 'more' })}
              </Button>
            </Stack>
          )}
        </Stack>
      )}
    </ReviewHeaderCard>
  );
};

export default CompletedReviewCard;
