import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Box, Typography } from '@mui/material';
import { DIDSpaceConnection, DIDSpaceConnect } from '@blocklet/did-space-react';
import { SpaceGateway, useConfigUserSpaceContext } from '../../../contexts/config-user-space';
import Action from './action';
import useMobile from '../../../hooks/use-mobile';

function Connected({ spaceGateway }: { spaceGateway: SpaceGateway | undefined }) {
  const { t } = useLocaleContext();
  const { updateSpaceGateway, session } = useConfigUserSpaceContext();
  const isMobile = useMobile();

  const onSuccess = ({ spaceGateway: _spaceGateway }: { spaceGateway: SpaceGateway }) =>
    updateSpaceGateway(_spaceGateway);

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
      }}>
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          marginBottom: '12px',
        }}>
        <Typography
          sx={{
            fontSize: '16px',
            fontWeight: 'bold',
          }}>
          {t('storage.spaces.connected.title')}
        </Typography>
        {!isMobile && <DIDSpaceConnect connectScope="user" session={session} onSuccess={onSuccess} />}
      </Box>
      <Box>
        {spaceGateway && (
          <DIDSpaceConnection
            key={spaceGateway.endpoint}
            endpoint={spaceGateway.endpoint}
            deps={[spaceGateway]}
            selected
            footer
            // eslint-disable-next-line react/no-unstable-nested-components
            action={(props) => <Action session={session} {...props} />}
          />
        )}
      </Box>
      {isMobile && (
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: 2 }}>
          <DIDSpaceConnect connectScope="user" session={session} onSuccess={onSuccess} />
        </Box>
      )}
    </Box>
  );
}

export default Connected;
