import { useTheme } from '@material-hu/mui/styles';

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

import useAuth from 'src/contexts/JWTContext';
import CertificatePreviewCanvas from 'src/pages/dashboard/Learning/Settings/Certificates/Create/components/CertificatePreviewCanvas';
import { CERTIFICATE_PREVIEW_ASPECT_RATIO } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/constants';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { type LearningCertificateListItem } from '../../types';
import { useGetLearningCertificate } from '../useGetLearningCertificate';

import { mapCertificateToPreviewProps } from './utils';

type CertificatePreviewDialogProps = {
  certificate: LearningCertificateListItem;
  onClose: () => void;
};

const CertificatePreviewDialog = ({
  certificate,
  onClose,
}: CertificatePreviewDialogProps) => {
  const { t } = useLokaliseTranslation('learning');
  const theme = useTheme();
  const { user, instance } = useAuth();

  const { data: certificateDetail, isLoading } = useGetLearningCertificate(
    certificate.id,
  );

  const previewProps = mapCertificateToPreviewProps(
    certificateDetail ?? certificate,
    {
      user,
      theme,
      instanceColor: instance?.color ?? undefined,
      t,
    },
  );

  return (
    <Dialog
      onClose={onClose}
      title={t('settings.certificates.preview.title', {
        certificateName: certificate.name,
      })}
      body={
        isLoading ? (
          <Skeleton
            variant="rounded"
            width="100%"
            sx={{
              height: 'auto',
              aspectRatio: CERTIFICATE_PREVIEW_ASPECT_RATIO,
              borderRadius: 2,
            }}
          />
        ) : (
          <CardContainer
            fullWidth
            color="grey"
          >
            <CertificatePreviewCanvas {...previewProps} />
          </CardContainer>
        )
      }
      primaryButtonProps={{
        children: t('general:close'),
        onClick: onClose,
      }}
    />
  );
};

export default CertificatePreviewDialog;
