import {
  as,
  Badge,
  Box,
  color,
  ContainerColor,
  MainColor,
  Text,
  Tooltip,
  TooltipProvider,
  toRem,
} from 'folds';
import React, { ReactNode } from 'react';
import * as css from './styles.css';
import { Presence, usePresenceLabel } from '../../hooks/useUserPresence';

const PresenceToColor: Record<Presence, MainColor> = {
  [Presence.Online]: 'Success',
  [Presence.Unavailable]: 'Warning',
  [Presence.Offline]: 'Secondary',
};

type PresenceBadgeProps = {
  presence: Presence;
  status?: string;
  size?: '200' | '300' | '400' | '500';
};
export function PresenceBadge({ presence, status, size }: PresenceBadgeProps) {
  const label = usePresenceLabel();
  // DND is encoded as unavailable + status_msg 'dnd'; render it red/"Do Not
  // Disturb" to match PresenceRingAvatar and the settings picker (which both
  // special-case 'dnd' → Critical) — the badge was the lone outlier showing a
  // yellow "Idle". The 'dnd' sentinel isn't surfaced as a status line.
  const isDnd = presence === Presence.Unavailable && status === 'dnd';
  const displayLabel = isDnd ? 'Do Not Disturb' : label[presence];
  const displayStatus = isDnd ? undefined : status;
  const ariaLabel = displayStatus ? `${displayLabel} — ${displayStatus}` : displayLabel;

  return (
    <TooltipProvider
      position="Right"
      align="Center"
      offset={4}
      delay={200}
      tooltip={
        <Tooltip>
          <Box style={{ maxWidth: toRem(250) }} alignItems="Baseline" gap="100">
            <Text size="L400">{displayLabel}</Text>
            {displayStatus && <Text size="T200">•</Text>}
            {displayStatus && <Text size="T200">{displayStatus}</Text>}
          </Box>
        </Tooltip>
      }
    >
      {(triggerRef) => (
        <Badge
          aria-label={ariaLabel}
          ref={triggerRef}
          size={size}
          variant={isDnd ? 'Critical' : PresenceToColor[presence]}
          fill={presence === Presence.Offline ? 'Soft' : 'Solid'}
          radii="Pill"
        />
      )}
    </TooltipProvider>
  );
}

type AvatarPresenceProps = {
  badge: ReactNode;
  variant?: ContainerColor;
};
export const AvatarPresence = as<'div', AvatarPresenceProps>(
  ({ as: AsAvatarPresence, badge, variant = 'Surface', children, ...props }, ref) => (
    <Box as={AsAvatarPresence} className={css.AvatarPresence} {...props} ref={ref}>
      {badge && (
        <div
          className={css.AvatarPresenceBadge}
          style={{ backgroundColor: color[variant].Container }}
        >
          {badge}
        </div>
      )}
      {children}
    </Box>
  ),
);
