import {
  type CertificateLogoDisplay,
  type CertificatePreviewProps,
  type CertificateSignatureDisplay,
} from 'src/pages/dashboard/Learning/Settings/Certificates/Create/components/CertificatePreviewCanvas/types';
import {
  convertFieldTokensToLocalized,
  getCertificateAccentHex,
  joinSignaturesWithAssets,
} from 'src/pages/dashboard/Learning/Settings/Certificates/Create/utils';
import { getFullname } from 'src/utils/userUtils';

import { CertificateColor } from '../../constants';
import {
  type CertificatePreviewContext,
  type LearningCertificateDTO,
} from '../../types';

/**
 * Converts a certificate entity and preview context into the props needed
 * to render the certificate preview UI. Handles mapping of accent color,
 * background image, alignment, recipient info, and collects signatures and logos.
 *
 * @param certificate - Detailed certificate DTO (with signed asset URLs)
 * @param context - Preview context (theme, instance color, recipient)
 * @returns CertificatePreviewProps for the certificate preview dialog
 */
export const mapCertificateToPreviewProps = (
  certificate: LearningCertificateDTO,
  context: CertificatePreviewContext,
): CertificatePreviewProps => {
  const { user, instanceColor, theme, t } = context;

  const accentColor = certificate.color ?? CertificateColor.COMMUNITY;

  const signatures: CertificateSignatureDisplay[] = joinSignaturesWithAssets(
    certificate.signatures,
    certificate.signaturesFileAssets,
  ).map(({ signature, asset }) => ({
    imageUrl: asset?.url,
    primaryText: signature.signerName ?? '',
    secondaryText: signature.signerTitle ?? '',
  }));

  const logos: CertificateLogoDisplay[] = (
    certificate.logoFileAssets ?? []
  ).map(asset => ({ imageUrl: asset.url }));

  return {
    templateId: certificate.type,
    accentColor,
    accentHex: getCertificateAccentHex(accentColor, theme, instanceColor),
    recipientName: getFullname({
      firstName: user?.firstName,
      lastName: user?.lastName,
    }),
    headingTitle: certificate.title,
    subtitle: certificate.subtitle
      ? convertFieldTokensToLocalized(certificate.subtitle, t)
      : '',
    description: certificate.description
      ? convertFieldTokensToLocalized(certificate.description, t)
      : '',
    textAlignment: certificate.alignment,
    signaturesEnabled: signatures.length > 0,
    signatures,
    logosEnabled: logos.length > 0,
    logos,
    backgroundImageUrl: certificate.pictureUrl ?? undefined,
  };
};
