import { DIDSpaceConnect, DIDSpaceGateway, DIDSpaceStatus } from '@blocklet/did-space-react';
import { IconButton, Link, Stack } from '@mui/material';
import Toast from '@arcblock/ux/lib/Toast';
import { OpenInNew as OpenInNewIcon } from '@mui/icons-material';
import { AxiosError } from 'axios';
import { getSpaceHomeUrl } from '../../../libs/spaces';
import { Session } from '../../../@types';
import { formatAxiosError } from '../../libs/utils';

function Action({
  session,
  spaceGateway,
  spaceStatus,
  refresh,
}: {
  session: Session;
  spaceGateway: DIDSpaceGateway;
  spaceStatus: DIDSpaceStatus;
  refresh: Function;
}) {
  return (
    <Stack direction="row" spacing={1}>
      {/* 重新连接 */}
      {spaceStatus === DIDSpaceStatus.DISCONNECTED && (
        <DIDSpaceConnect
          reconnect
          variant="outlined"
          session={session}
          spaceDid={session.user?.didSpace?.did}
          spaceGatewayUrl={session.user?.didSpace?.url}
          connectScope="user"
          onSuccess={async () => {
            await refresh();
          }}
          onError={(error) => {
            console.error(error);
            Toast.error(formatAxiosError(error as AxiosError));
          }}
        />
      )}
      {/* 打开空间 */}
      <IconButton size="small" LinkComponent={Link} href={getSpaceHomeUrl(spaceGateway.endpoint)} target="_blank">
        <OpenInNewIcon />
      </IconButton>
    </Stack>
  );
}

export default Action;
