import PropTypes from 'prop-types';
import { useImperativeHandle, useRef } from 'react';
import { useMemoizedFn } from 'ahooks';
import { LOGIN_PROVIDER } from '@arcblock/ux/lib/Util/constant';

import PasskeyActions from '../../../Passkey/actions';
import { getAppId } from '../../../utils';
import { useStateContext } from '../../contexts/state';

export default function PasskeyLoginItem({ ref = null, onSuccess, tokenState, behavior = 'none', ...rest }) {
  const { extraParams, lastLoginMethod } = useStateContext();
  const passkeyActionRef = useRef(null);

  const handleSuccess = useMemoizedFn((result) =>
    onSuccess(
      {
        ...result,
        encrypted: false,
      },
      (val) => val,
      {
        sourceAppPid: extraParams?.sourceAppPid,
        connected_app: getAppId(tokenState.appInfo, tokenState.memberAppInfo),
      }
    )
  );

  useImperativeHandle(ref, () => ({
    connect: passkeyActionRef.current.click,
  }));

  if (behavior === 'none') {
    return null;
  }

  return (
    <PasskeyActions
      {...rest}
      ref={passkeyActionRef}
      isLatest={lastLoginMethod && lastLoginMethod === LOGIN_PROVIDER.PASSKEY}
      action={tokenState.action}
      behavior={behavior}
      onSuccess={handleSuccess}
      extraParams={extraParams}
    />
  );
}

PasskeyLoginItem.propTypes = {
  onSuccess: PropTypes.func.isRequired,
  tokenState: PropTypes.object.isRequired,
  behavior: PropTypes.oneOf(['none', 'both', 'only-existing', 'only-new']),
  ref: PropTypes.any,
};
