import { FC, useState } from 'react';

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

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

import RichText from 'src/pages/dashboard/performance/components/RichText';
import { type ServiceItem } from 'src/pages/dashboard/serviceManagement/types';
import { truncateHTML } from 'src/utils/feed';
import { useLokaliseTranslation } from 'src/utils/i18n';

import TypographyLinkSensitive from '../../../general/TypographyLinkSensitive';

export type DescriptionProps = {
  serviceItem?: ServiceItem;
};

const Description: FC<DescriptionProps> = ({ serviceItem: catalogItem }) => {
  const { t } = useLokaliseTranslation('service_management');

  const [showFullRichText, setShowFullRichText] = useState(false);

  // Limit the initial display of the rich text to 150 characters and 2 lines
  const { htmlTruncated, isTruncated } = truncateHTML(
    catalogItem?.richDescription ?? '',
    150,
    2,
  );

  return (
    <CardContainer fullWidth>
      <Typography
        variant="globalS"
        fontWeight="fontWeightSemiBold"
      >
        {t('description')}
      </Typography>
      <Stack sx={{ gap: 0.5 }}>
        <TypographyLinkSensitive
          variant="body1"
          color="text.primary"
          sx={{
            display: 'block',
            wordBreak: 'break-word',
            overflowWrap: 'break-word',
          }}
        >
          {catalogItem?.description}
        </TypographyLinkSensitive>
        {catalogItem?.richDescription && (
          <Stack>
            <RichText
              sx={{
                display: 'block',
                wordBreak: 'break-word',
                overflowWrap: 'break-word',
              }}
              openLinksInNewTab
              text={
                showFullRichText ? catalogItem?.richDescription : htmlTruncated
              }
            />
            {isTruncated && (
              <Button
                variant="secondary"
                onClick={() => setShowFullRichText(!showFullRichText)}
                sx={{
                  alignSelf: 'flex-start',
                }}
              >
                {showFullRichText ? t('read_less') : t('read_more')}
              </Button>
            )}
          </Stack>
        )}
      </Stack>
    </CardContainer>
  );
};

export default Description;
