import { Box, TextField } from '@mui/material';
import { useMemoizedFn, useReactive } from 'ahooks';
import Toast from '@arcblock/ux/lib/Toast';

import { client } from '../../libs/client';
import { User } from '../../@types';
import { formatAxiosError } from '../libs/utils';

export default function ConfigInviter({ user }: { user: User }) {
  const currentState = useReactive({
    inviter: user?.inviter,
    loading: false,
  });

  const handleChange = useMemoizedFn(async (e) => {
    try {
      const { value } = e.target;
      currentState.loading = true;
      await client.user.saveProfile({ inviter: value });
      currentState.inviter = value;
    } catch (err) {
      Toast.error(formatAxiosError(err as any));
    } finally {
      currentState.loading = false;
    }
  });

  if (!user) {
    return '-';
  }

  const inviteEnabled = !!window.blocklet?.settings?.invite?.enabled;
  if (!inviteEnabled) {
    return '-';
  }

  const hasInviter = !!user.inviter;
  if (hasInviter) {
    return '-';
  }

  return (
    <Box>
      <TextField size="small" fullWidth label="" value={currentState.inviter} onChange={handleChange} />
    </Box>
  );
}
