import { LiteralUnion } from 'type-fest';
import { alpha, Theme, Typography, useTheme } from '@mui/material';
import { Icon } from '@iconify/react';
import { AppBadgeDefaultProps, BadgeContainer } from './app-badge-default';

export type ColorKey = 'primary' | 'info' | 'success' | 'error' | 'warning';
export type BadgeColor = LiteralUnion<ColorKey, string>;
export const colorMap: Record<ColorKey, (theme: Theme) => { main: string }> = {
  primary: (theme) => theme.palette.primary,
  info: (theme) => theme.palette.info,
  success: (theme) => theme.palette.success,
  error: (theme) => theme.palette.error,
  warning: (theme) => theme.palette.warning,
};

export const getBgColor = (theme: Theme, color: BadgeColor): string => {
  if (colorMap[color as ColorKey]) {
    const c = colorMap[color as ColorKey](theme).main;
    return alpha(c, 0.1);
  }
  return alpha(color, 0.1);
};

export const getTextColor = (theme: Theme, color: BadgeColor): string => {
  if (colorMap[color as ColorKey]) {
    return colorMap[color as ColorKey](theme).main;
  }
  return color;
};

export interface AppBadgeVersionProps extends AppBadgeDefaultProps {
  color?: string | ColorKey;
}

export function AppBadgeVersion({
  icon = '',
  value = '',
  color = 'info',
  loading = false,
  ...rest
}: AppBadgeVersionProps) {
  const theme = useTheme();
  const txtcolor = getTextColor(theme, color);
  const bgcolor = getBgColor(theme, color);

  return (
    <BadgeContainer
      loading={loading}
      sx={{
        borderColor: alpha(txtcolor, 0.2),
        bgcolor,
      }}
      {...rest}>
      <Icon icon={icon || 'lucide:orbit'} style={{ marginRight: 6 }} />
      <Typography className="app-badge-value" style={{ color: txtcolor }}>
        v {value}
      </Typography>
    </BadgeContainer>
  );
}
