import { useMemo } from 'react';
import { useBrandSettings } from '@hubspot/cms-components';
import { dummyLogoData } from './_dummyLogoData.js';
import ContentFields from './ContentFields.js';
import { LogoData, LogoProps } from './types.js';
import styles from './index.module.scss';
import cx from '../utils/classname.js';
import Link from '../Link/index.js';
import Image from '../Image/index.js';

export const Logo = ({
  useDummyLogo = false,
  companyName,
  className = '',
  style = {},
  loading = 'eager',
  maxWidth,
  maxHeight,
}: LogoProps) => {
  const { primaryLogo } = useBrandSettings() ?? {};

  const logo: LogoData | undefined = useMemo(
    () => (useDummyLogo ? dummyLogoData.logo : primaryLogo),
    [useDummyLogo, primaryLogo]
  );

  const hasLogoSrc = !!logo?.src;

  if (!hasLogoSrc && !companyName) {
    return null;
  }

  const hasOnlyMaxHeight = maxHeight && !maxWidth;

  const defaultClasses = styles.logo;
  const combinedClasses = cx(defaultClasses, className);
  const imageClasses = styles.logoImage;

  const wrapperStyle: React.CSSProperties = {
    ...(maxWidth && { maxInlineSize: maxWidth }),
    ...(maxHeight && { maxBlockSize: maxHeight }),
    ...(hasOnlyMaxHeight && { maxInlineSize: 'fit-content' }),
    ...style,
  };

  const imageStyle: React.CSSProperties = {
    ...(hasOnlyMaxHeight && {
      inlineSize: 'auto',
      blockSize: 'auto',
    }),
  };

  const content = hasLogoSrc ? (
    <Image
      src={logo.src}
      alt={logo.alt ?? 'Logo'}
      loading={loading}
      width={logo.width}
      height={logo.height}
      className={imageClasses}
      style={imageStyle}
      responsive={true}
    />
  ) : (
    <span className={styles.companyName}>{companyName}</span>
  );

  return logo?.link ? (
    <Link href={logo.link} className={combinedClasses} style={wrapperStyle}>
      {content}
    </Link>
  ) : (
    <div className={combinedClasses} style={wrapperStyle}>
      {content}
    </div>
  );
};

type LogoComponentType = typeof Logo & {
  ContentFields: typeof ContentFields;
};

const LogoWithFields = Logo as LogoComponentType;
LogoWithFields.ContentFields = ContentFields;

export default LogoWithFields;
