import {
  oauthLoginUrl,
  oauthHandleRedirectIfPresent,
  whoAmI,
} from '@huggingface/hub';
import { useEffect } from 'react';
import { isDev, testToken } from '../utils/utils';

const login = async () => {
  const url = await oauthLoginUrl();
  window.location.href = url;
};

export const AuthCard = ({
  setHfToken,
  hfToken,
}: {
  setHfToken: (token: string) => void;
  hfToken: string;
}) => {
  useEffect(() => {
    const checkToken = async () => {
      if (isDev) {
        console.log({ testToken });
        return setHfToken(testToken);
      }
      const res = await oauthHandleRedirectIfPresent();
      console.log('oauthHandleRedirectIfPresent', res);
      if (res) {
        try {
          const myself = await whoAmI({ accessToken: res.accessToken });
          console.log('myself', myself);
        } catch (e) {
          console.log(e);
          return setHfToken('');
        }
        return setHfToken(res.accessToken);
      } else {
        return setHfToken('');
      }
    };
    checkToken();
  }, []);

  const isOK = hfToken && hfToken.startsWith('hf_');

  return (
    <div className="card bg-base-100 w-full shadow-xl">
      <div className="card-body">
        <h2 className="card-title">
          Step 0: Sign in to use Inference Providers
        </h2>
        <div>
          {isOK ? (
            <button className="btn">✅ Nice, you are signed in</button>
          ) : (
            <button className="btn btn-primary" onClick={login}>
              🤗 Sign in with Hugging Face
            </button>
          )}
        </div>
      </div>
    </div>
  );
};
