import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import type { PaymentDetails, TPaymentMethod } from '@blocklet/payment-types';
import { OpenInNewOutlined } from '@mui/icons-material';
import { Link, Stack, Typography } from '@mui/material';
import { styled } from '@mui/system';

import { getTxLink } from '../../libs/util';

export default function TxLink({
  details,
  method,
  mode = 'dashboard',
  align = 'left',
  size = 20,
}: {
  details: PaymentDetails;
  method: TPaymentMethod;
  mode?: 'customer' | 'dashboard';
  align?: 'left' | 'right';
  size?: number;
}) {
  const { t } = useLocaleContext();

  if (!details || (mode === 'customer' && method.type === 'stripe')) {
    return (
      <Typography
        component="small"
        sx={{
          color: 'text.secondary',
        }}>
        {t('common.none')}
      </Typography>
    );
  }

  const { text, link } = getTxLink(method, details);

  if (link && text) {
    return (
      <Link href={link} target="_blank" rel="noopener noreferrer">
        <Root
          direction="row"
          alignItems="center"
          justifyContent={align === 'left' ? 'flex-start' : 'flex-end'}
          sx={{ color: 'text.link' }}
          spacing={1}>
          <Typography className="tx-link-text" component="span" sx={{ color: 'text.link' }}>
            {text.length > 40 ? [text.slice(0, 6), text.slice(-6)].join('...') : text}
          </Typography>
          <OpenInNewOutlined fontSize="small" sx={{ width: size, height: size }} />
        </Root>
      </Link>
    );
  }

  return (
    <Typography
      component="small"
      sx={{
        color: 'text.secondary',
      }}>
      {t('common.none')}
    </Typography>
  );
}

const Root = styled(Stack)`
  @media (max-width: 600px) {
    svg.MuiSvgIcon-root {
      display: none !important;
    }
  }
`;
