import React from 'react';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import localizedFormat from 'dayjs/plugin/localizedFormat';
import 'dayjs/locale/zh';
import 'dayjs/locale/zh-tw';
import 'dayjs/locale/ja';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { AppBadgeDefault, AppBadgeDefaultProps } from './badges/app-badge-default';
import { AppBadgeSwitch, AppBadgeSwitchProps } from './badges/app-badge-switch';
import { AppBadgeVersion, AppBadgeVersionProps } from './badges/app-badge-version';
import { AppBadgeState, AppBadgeStateProps } from './badges/app-badge-state';
import { AppBadgeDID, AppBadgeDIDProps } from './badges/app-badge-did';

dayjs.extend(relativeTime);
dayjs.extend(localizedFormat);

export const formatNumber = (num: unknown, round: number = 0): string => {
  if (typeof num !== 'number') return '';

  const absNum = Math.abs(num);
  let rounded;
  let unit = '';

  if (absNum >= 1e12) {
    unit = 'T';
    rounded = `${(num / 1e12).toFixed(round)}`; // 万亿
  } else if (absNum >= 1e9) {
    unit = 'B';
    rounded = `${(num / 1e9).toFixed(round)}`; // 十亿
  } else if (absNum >= 1e6) {
    unit = 'M';
    rounded = `${(num / 1e6).toFixed(round)}`; // 百万
  } else if (absNum >= 1e3) {
    unit = 'K';
    rounded = `${(num / 1e3).toFixed(round)}`; // 千
  } else {
    rounded = num.toString();
  }

  // 去掉尾部的零
  if (round > 0) {
    rounded = rounded.replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
  }

  return `${rounded}${unit}`;
};

export const formatTime = (value?: string | number | Date, locale: string = 'en'): string => {
  if (!value) return '';

  return dayjs(value).locale(locale).fromNow();
};

const BadgeVariants: Record<string, React.ComponentType<any>> = {
  switch: AppBadgeSwitch,
  version: AppBadgeVersion,
  state: AppBadgeState,
  did: AppBadgeDID,
};

export type AppBadgeProps =
  | (AppBadgeDefaultProps & { variant?: 'default' })
  | (AppBadgeDefaultProps & { variant: 'number' })
  | (Omit<AppBadgeDefaultProps, 'value'> & { variant: 'time'; value?: string | number | Date })
  | (AppBadgeSwitchProps & { variant: 'switch' })
  | (AppBadgeVersionProps & { variant: 'version' })
  | (AppBadgeStateProps & { variant: 'state' })
  | (AppBadgeDIDProps & { variant: 'did' });

export default function AppBadge(props: AppBadgeProps) {
  const { locale = 'en' } = useLocaleContext() || {};

  if (props.variant === 'number') {
    const { value, round = 0, ...rest } = props;
    const val = formatNumber(Number(value), round);

    return <AppBadgeDefault value={val} {...rest} />;
  }
  if (props.variant === 'time') {
    const { value, ...rest } = props;
    const val = formatTime(value, locale);

    return <AppBadgeDefault value={val} {...rest} />;
  }
  if (props.variant) {
    const Badge = BadgeVariants[props.variant];
    if (Badge) {
      return <Badge {...props} />;
    }
  }

  return <AppBadgeDefault {...(props as AppBadgeDefaultProps)} />;
}
