import { use } from 'react';
import { Box, Button, Typography } from '@mui/material';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { useMemoizedFn } from 'ahooks';
import { useConfirm } from '@arcblock/ux/lib/Dialog';
import { SessionContext } from '@arcblock/did-connect-react/lib/Session';
import Toast from '@arcblock/ux/lib/Toast';

import { translations } from '../libs/locales';
import type { SessionContext as TSessionContext } from '../../@types';

export default function DangerZone({ onDestroySelf = undefined }: { onDestroySelf?: () => void }) {
  const { confirmHolder } = useConfirm();

  const { locale } = useLocaleContext();
  const { session } = use<TSessionContext>(SessionContext);
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });

  const handleRemoveMyself = useMemoizedFn(async () => {
    if (!onDestroySelf || typeof onDestroySelf !== 'function') {
      return;
    }

    const handle = session.withSecondaryAuth(onDestroySelf, {
      extraParams: {
        locale,
        removeUserDid: session?.user?.did,
        input: {
          user: { did: session?.user?.did },
          teamDid: window?.blocklet?.did,
        },
      },
      operation: 'destroySelf',
    });
    try {
      await handle();
      session.logout();
    } catch (error: any) {
      Toast.error(error?.message || t('destroyMyself.error'));
    }
  });

  return (
    <>
      <Box>
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            justifyContent: 'space-between',
            flexWrap: 'wrap',
          }}>
          <Box>
            <Typography
              variant="h6"
              sx={{
                fontSize: '0.875rem !important',
                fontWeight: 'bold',
              }}>
              {t('dangerZone.deleteAccount')}
            </Typography>
            <Typography
              variant="caption"
              sx={{
                color: 'text.secondary',
              }}>
              {t('dangerZone.deleteAccountDescription')}
            </Typography>
          </Box>
          <Button variant="contained" color="error" size="small" onClick={handleRemoveMyself}>
            {t('dangerZone.delete')}
          </Button>
        </Box>
      </Box>
      {confirmHolder}
    </>
  );
}
