import React, { CSSProperties, useMemo } from 'react';
import { Text, as } from 'folds';
import classNames from 'classnames';
import * as css from './layout.css';
import { isStationeryTheme, useTheme } from '../../../hooks/useTheme';
import { STATIONERY_NAME_INK } from '../../../utils/paperSafeInk';

export const MessageBase = as<'div', css.MessageBaseVariants>(
  ({ className, highlight, selected, collapse, autoCollapse, space, newMessage, ...props }, ref) => (
    <div
      className={classNames(
        css.MessageBase({ highlight, selected, collapse, autoCollapse, space, newMessage }),
        className
      )}
      data-message-collapsed={collapse ? '' : undefined}
      {...props}
      ref={ref}
    />
  )
);

export const AvatarBase = as<'span'>(({ className, ...props }, ref) => (
  <span
    className={classNames(css.AvatarBase, className)}
    data-message-avatar=""
    {...props}
    ref={ref}
  />
));

export const Username = as<'span'>(({ as: AsUsername = 'span', className, style, ...props }, ref) => {
  const theme = useTheme();
  const isStationery = isStationeryTheme(theme);
  const userColor =
    typeof (style as CSSProperties | undefined)?.color === 'string'
      ? ((style as CSSProperties).color as string)
      : undefined;

  const safeStyle = useMemo((): CSSProperties | undefined => {
    if (!isStationery) return style as CSSProperties | undefined;
    return {
      ...(style as CSSProperties | undefined),
      // Name in ink; keep their color as an accent underline
      color: STATIONERY_NAME_INK,
      ...(userColor
        ? { ['--username-accent' as string]: userColor, textDecorationColor: userColor }
        : null),
    };
  }, [style, isStationery, userColor]);

  return (
    <AsUsername
      className={classNames(css.Username, className)}
      data-message-username=""
      data-username-accent={isStationery && userColor ? '' : undefined}
      style={safeStyle}
      {...props}
      ref={ref}
    />
  );
});

export const UsernameBold = as<'b'>(({ as: AsUsernameBold = 'b', className, ...props }, ref) => (
  <AsUsernameBold className={classNames(css.UsernameBold, className)} {...props} ref={ref} />
));

export const MessageTextBody = as<'div', css.MessageTextBodyVariants & { notice?: boolean }>(
  ({ as: asComp = 'div', className, preWrap, jumboEmoji, emote, notice, ...props }, ref) => (
    <Text
      as={asComp}
      size={jumboEmoji ? 'Inherit' : 'T400'}
      priority={notice ? '300' : '400'}
      className={classNames(css.MessageTextBody({ preWrap, jumboEmoji, emote }), className)}
      data-allow-text-selection="true"
      data-message-body=""
      data-jumbo-emoji={jumboEmoji ? '' : undefined}
      {...props}
      ref={ref}
    />
  )
);
