import PropTypes from 'prop-types';
import { useMemoizedFn } from 'ahooks';
import mailFilledIcon from '@iconify-icons/tabler/mail-filled';
import { LOGIN_PROVIDER, LOGIN_PROVIDER_NAME } from '@arcblock/ux/lib/Util/constant';
import { GA_LAST_LOGIN_METHOD } from '@arcblock/ux/lib/withTracker/constant';

import LoginMethodItem from '../../components/login-item/login-method-item';
import { useStateContext } from '../../contexts/state';

export default function EmailListItem({ ...rest }) {
  const { setSelectedPlugin, getPlugin, connectState, lastLoginMethod } = useStateContext();
  const handleConnect = useMemoizedFn(() => {
    localStorage.setItem(GA_LAST_LOGIN_METHOD, LOGIN_PROVIDER.EMAIL);
    const plugin = getPlugin(LOGIN_PROVIDER.EMAIL);
    plugin.state.reset();
    plugin.state.status = 'creating';
    connectState.chooseMethod = LOGIN_PROVIDER.EMAIL;
    setSelectedPlugin(plugin);
  });

  return (
    <LoginMethodItem
      {...rest}
      isLatest={lastLoginMethod && lastLoginMethod === LOGIN_PROVIDER.EMAIL}
      title={LOGIN_PROVIDER_NAME[LOGIN_PROVIDER.EMAIL]}
      icon={mailFilledIcon}
      onClick={handleConnect}
    />
  );
}

EmailListItem.propTypes = {
  onClick: PropTypes.func,
};
