import { Button, ButtonProps } from '@tarojs/components';

import classNames from 'classnames';
import { useCallback, useState } from 'react';

import LoginDialog from '@/components/login-dialog';
import useUserInfo from '@/hooks/use-user-info';
import { isNeedLogin } from '@/utils/user';

import './index.less';

export enum BindPhoneStatus {
  Success,
  Cancel,
  Error,
}

export interface ILoginButtonProps extends ButtonProps {
  needPhone?: boolean;
}

const PREFIX = 'login-button';

function LoginButton(props: ILoginButtonProps) {
  const { className, children, needPhone, onClick, ...otherProps } = props;
  const userInfo = useUserInfo();
  const [visible, setVisible] = useState(false);
  const needLogin = isNeedLogin(userInfo);

  const onSuccess = useCallback(
    e => {
      setVisible(false);
      onClick?.(e);
    },
    [onClick]
  );

  return (
    <>
      <Button
        {...otherProps}
        className={classNames(PREFIX, className)}
        onClick={needLogin ? () => setVisible(true) : onClick}
      >
        {children}
      </Button>
      {visible && <LoginDialog onCancel={() => setVisible(false)} onSuccess={onSuccess} needPhone={needPhone} />}
    </>
  );
}

export default LoginButton;
