import PropTypes from 'prop-types';
import { useCreation, useMemoizedFn } from 'ahooks';
import { Box, Skeleton, Typography, useTheme } from '@mui/material';
import { alpha, styled } from '@mui/material/styles';
import { Icon } from '@iconify/react';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import dayjs from '@abtnode/util/lib/dayjs';
import DidAddress from '@arcblock/ux/lib/Address/did-address';
import { isEthereumDid } from '@arcblock/ux/lib/Util';
import { Link } from 'react-router-dom';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const colorMap = {
  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
};
const getBgColor = (theme, color) => {
  if (colorMap[color]) {
    const c = colorMap[color](theme).main;
    return alpha(c, 0.1);
  }
  return alpha(color, 0.1);
};
const getTextColor = (theme, color) => {
  if (colorMap[color]) {
    return colorMap[color](theme).main;
  }
  return color;
};
const formatNumber = (num, round = 0) => {
  if (num === null || num === undefined || Number.isNaN(num)) return '';
  const absNum = Math.abs(num);
  let formatted;
  if (absNum >= 1e12) {
    formatted = `${(num / 1e12).toFixed(round)}T`; // 万亿
  } else if (absNum >= 1e9) {
    formatted = `${(num / 1e9).toFixed(round)}B`; // 十亿
  } else if (absNum >= 1e6) {
    formatted = `${(num / 1e6).toFixed(round)}M`; // 百万
  } else if (absNum >= 1e3) {
    formatted = `${(num / 1e3).toFixed(round)}K`; // 千
  } else {
    formatted = num.toString();
  }

  // 去掉尾部的零
  if (round > 0) {
    formatted = formatted.replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
  }
  return formatted;
};
const formatTime = (value, locale = 'en') => dayjs(value).locale(locale).fromNow();
const isExternal = (to = '') => {
  return to.startsWith('http:') || to.startsWith('https:');
};
const isSameOrigin = to => {
  try {
    const url = new URL(to);
    return url.origin === window.location.origin;
  } catch {
    return false;
  }
};
const StateIcon = styled('span')(({
  theme,
  color
}) => {
  return {
    position: 'relative',
    display: 'inline-block',
    width: theme.spacing(1),
    height: theme.spacing(1),
    borderRadius: '50%',
    backgroundColor: color,
    marginRight: theme.spacing(1)
  };
});
const StyledBadge = styled(Box)(({
  theme
}) => ({
  position: 'relative',
  display: 'inline-flex',
  alignItems: 'center',
  height: theme.spacing(3),
  paddingLeft: theme.spacing(1.5),
  paddingRight: theme.spacing(1.5),
  border: '1px solid',
  borderColor: theme.palette.divider,
  borderRadius: theme.shape.borderRadius * 0.5,
  fontSize: 12,
  overflow: 'hidden',
  '& .app-badge-label': {
    display: 'inline-flex',
    gap: theme.spacing(1),
    alignItems: 'center',
    lineHeight: theme.spacing(3),
    marginLeft: theme.spacing(-1.5),
    paddingLeft: theme.spacing(1.5),
    marginRight: theme.spacing(1),
    fontSize: 12,
    backgroundColor: theme.palette.grey[100],
    color: theme.palette.text.secondary,
    '&::after': {
      content: '""',
      height: theme.spacing(3),
      borderRight: '1px solid',
      borderColor: theme.palette.divider,
      backgroundColor: theme.palette.grey[100]
    }
  },
  '& .app-badge-value': {
    color: theme.palette.text.primary,
    fontSize: 12
  }
}));
function BadgeContainer({
  loading = false,
  children = null,
  to = '',
  ...rest
}) {
  const container = /*#__PURE__*/_jsx(StyledBadge, {
    className: "app-badge",
    component: to ? 'a' : 'div',
    href: to,
    ...rest,
    children: children
  });
  if (loading) {
    return /*#__PURE__*/_jsx(Skeleton, {
      variant: "rounded",
      children: container
    });
  }
  if (to) {
    if (isExternal(to)) {
      const target = isSameOrigin(to) ? '_self' : '_blank';

      // 外部链接跳转
      return /*#__PURE__*/_jsx(StyledBadge, {
        className: "app-badge",
        component: "a",
        href: to,
        target: target,
        rel: "noreferrer noopener",
        ...rest,
        children: children
      });
    }

    // 内部路由跳转
    return /*#__PURE__*/_jsx(StyledBadge, {
      className: "app-badge",
      component: Link,
      to: to,
      ...rest,
      children: children
    });
  }

  // 无跳转
  return /*#__PURE__*/_jsx(StyledBadge, {
    className: "app-badge",
    ...rest,
    children: children
  });
}
BadgeContainer.propTypes = {
  loading: PropTypes.bool,
  to: PropTypes.string,
  children: PropTypes.node
};
function AppBadgeState({
  value = '',
  color = 'primary',
  loading = false,
  ...rest
}) {
  const theme = useTheme();
  const txtcolor = getTextColor(theme, color);
  const bgcolor = getBgColor(theme, color);
  return /*#__PURE__*/_jsxs(BadgeContainer, {
    loading: loading,
    sx: {
      borderColor: alpha(txtcolor, 0.2),
      bgcolor
    },
    ...rest,
    children: [/*#__PURE__*/_jsx(StateIcon, {
      color: getTextColor(theme, color)
    }), /*#__PURE__*/_jsx(Typography, {
      className: "app-badge-value",
      style: {
        color: txtcolor
      },
      children: value
    })]
  });
}
AppBadgeState.propTypes = {
  value: PropTypes.string,
  color: PropTypes.string,
  loading: PropTypes.bool
};
function AppBadgeVersion({
  icon = '',
  value = '',
  color = 'info',
  loading = false,
  ...rest
}) {
  const theme = useTheme();
  const txtcolor = getTextColor(theme, color);
  const bgcolor = getBgColor(theme, color);
  return /*#__PURE__*/_jsxs(BadgeContainer, {
    loading: loading,
    sx: {
      borderColor: alpha(txtcolor, 0.2),
      bgcolor
    },
    ...rest,
    children: [/*#__PURE__*/_jsx(Icon, {
      icon: icon || 'lucide:orbit',
      style: {
        marginRight: 6
      }
    }), /*#__PURE__*/_jsxs(Typography, {
      className: "app-badge-value",
      style: {
        color: txtcolor
      },
      children: ["v ", value]
    })]
  });
}
AppBadgeVersion.propTypes = {
  icon: PropTypes.string,
  value: PropTypes.string,
  color: PropTypes.string,
  loading: PropTypes.bool
};
function AppBadgeDID({
  value = '',
  loading = false,
  ...rest
}) {
  const label = useCreation(() => {
    const isEthDid = isEthereumDid(value);
    return `DID:${isEthDid ? 'ETH' : 'ABT'}`;
  }, [value]);
  return /*#__PURE__*/_jsxs(BadgeContainer, {
    loading: loading,
    ...rest,
    children: [/*#__PURE__*/_jsx(Typography, {
      className: "app-badge-label",
      children: label
    }), /*#__PURE__*/_jsx(Typography, {
      className: "app-badge-value",
      children: /*#__PURE__*/_jsx(DidAddress, {
        did: value,
        inline: true,
        size: 14,
        compact: true,
        responsive: false
      })
    })]
  });
}
AppBadgeDID.propTypes = {
  value: PropTypes.string,
  loading: PropTypes.bool
};
function AppBadgeSwitch({
  label = '',
  value = undefined,
  trueValue = true,
  falseValue = false,
  loading = false,
  onChange = undefined,
  ...rest
}) {
  const theme = useTheme();
  let checked = false;
  const handleClick = useMemoizedFn(() => onChange?.(!checked));
  if (value === trueValue) {
    checked = true;
  } else if (value === falseValue) {
    checked = false;
  } else {
    checked = Boolean(value);
  }
  return /*#__PURE__*/_jsxs(BadgeContainer, {
    loading: loading,
    sx: {
      cursor: 'pointer',
      backgroundColor: checked ? 'primary.main' : 'grey.100',
      transition: 'background-color 0.3s ease'
    },
    onClick: handleClick,
    ...rest,
    children: [/*#__PURE__*/_jsx(Typography, {
      sx: {
        fontWeight: 400,
        paddingLeft: checked ? 0 : theme.spacing(4),
        paddingRight: checked ? theme.spacing(4) : 0,
        color: checked ? 'common.white' : 'text.secondary',
        transition: 'color 0.3s ease'
      },
      children: label
    }), /*#__PURE__*/_jsx(Box, {
      sx: {
        width: theme.spacing(3),
        height: theme.spacing(3),
        borderRadius: `${theme.shape.borderRadius * 0.5}px`,
        backgroundColor: 'common.white',
        position: 'absolute',
        top: '50%',
        left: checked ? `calc(100% - ${theme.spacing(4)})` : theme.spacing(1),
        transform: 'translateY(-50%)',
        transition: 'left 0.3s ease',
        boxShadow: 1
      }
    })]
  });
}
AppBadgeSwitch.propTypes = {
  label: PropTypes.string,
  value: PropTypes.any,
  trueValue: PropTypes.any,
  falseValue: PropTypes.any,
  loading: PropTypes.bool,
  onChange: PropTypes.func
};
export function AppBadgeDefault({
  icon = '',
  label = '',
  value = '',
  loading = false,
  ...rest
}) {
  return /*#__PURE__*/_jsxs(BadgeContainer, {
    loading: loading,
    ...rest,
    children: [label && /*#__PURE__*/_jsxs(Typography, {
      className: "app-badge-label",
      children: [icon && /*#__PURE__*/_jsx(Icon, {
        icon: icon
      }), label]
    }), /*#__PURE__*/_jsx(Typography, {
      className: "app-badge-value",
      children: value
    })]
  });
}
AppBadgeDefault.propTypes = {
  icon: PropTypes.string,
  label: PropTypes.string,
  value: PropTypes.string,
  loading: PropTypes.bool
};
const BadgeVariants = {
  switch: AppBadgeSwitch,
  version: AppBadgeVersion,
  state: AppBadgeState
};
export default function AppBadge({
  variant = 'default',
  ...props
}) {
  const Badge = BadgeVariants[variant];
  const {
    locale
  } = useLocaleContext();
  if (Badge) {
    return /*#__PURE__*/_jsx(Badge, {
      ...props
    });
  }
  if (variant === 'number') {
    const {
      value,
      round = 0,
      ...rest
    } = props;
    const val = formatNumber(Number(value), round);
    return /*#__PURE__*/_jsx(AppBadgeDefault, {
      value: val,
      ...rest
    });
  }
  if (variant === 'time') {
    const {
      value,
      ...rest
    } = props;
    const val = formatTime(value, locale);
    return /*#__PURE__*/_jsx(AppBadgeDefault, {
      value: val,
      ...rest
    });
  }
  return /*#__PURE__*/_jsx(AppBadgeDefault, {
    ...props
  });
}
AppBadge.propTypes = {
  variant: PropTypes.string,
  value: PropTypes.any,
  round: PropTypes.number,
  loading: PropTypes.bool,
  onChange: PropTypes.func,
  icon: PropTypes.node,
  label: PropTypes.string,
  trueValue: PropTypes.any,
  falseValue: PropTypes.any,
  color: PropTypes.string
};