import * as React from 'react';
import * as PropTypes from 'prop-types';

import classNames from '../../utils/classnames';
import { getCloudInstance } from '../../utils/tcb';

import {
  CloudbaseAuthenticator,
  onAuthUIStateChange,
  AUTHSTATE,
  LOGINTYPE,
  CloudbaseSignOut,
} from '@cloudbase/ui-react';

export default function Auth({ className }) {
  const cls = classNames({
    [className]: className,
  });

  const [authState, setAuthState] = React.useState(AUTHSTATE.SignIn);
  const [user, setUser] = React.useState({});
  const [tcb, setTcb] = React.useState(undefined);

  React.useEffect(() => {
    async function createTcb() {
      // 创建Tcb实例
      const app = await getCloudInstance();
      setTcb(app);
      // console.log('<<<<<weda', app);

      onAuthUIStateChange(app, (nextAuthState, authData) => {
        // console.log('call');
        // console.log('<<<<<nextAuthState', nextAuthState);
        // console.log('<<<<<authData', authData);
        setAuthState(nextAuthState);
        setUser(authData);
      });
    }
    createTcb();
  }, []);

  // console.log('<<<<<<<wedaaaa', tcb);

  return tcb ? (
    authState === AUTHSTATE.SignedIn && user ? (
      <div className={cls}>
        <header className="tcb-header">
          {/* Hello, {user.uid} */}
          <CloudbaseSignOut app={tcb}></CloudbaseSignOut>
        </header>
      </div>
    ) : (
      <div className={cls}>
        <CloudbaseAuthenticator
          userLoginType={LOGINTYPE.PHONE}
          isUsePassword={false}
          app={tcb}
        />
      </div>
    )
  ) : null;
}

Auth.propTypes = {
  className: PropTypes.string,
};
