import { CredentialResponse, GoogleLogin } from '@react-oauth/google';
import { FC, useEffect, useState } from 'react';
import { LoginRequest, LoginResponse, User } from './types';
import ElementList from './components/ElementList';

const App: FC = () => {
  const [user, setUser] = useState<User | undefined>(undefined);

  useEffect(() => {
    const userString = localStorage.getItem('user');
    if (userString == null) {
      return;
    }

    setUser(JSON.parse(userString));
  }, []);

  const login = async (credentials: CredentialResponse) => {
    if (credentials.credential == null) {
      console.log('Error getting credentials from google');
      return;
    }

    // Authenticate with API and get user ID
    const loginRequest: LoginRequest = {
      googleToken: credentials.credential,
    };
    const loginResponse = await fetch('/api/auth/login', {
      method: 'POST',
      credentials: 'include',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(loginRequest),
    });
    if (!loginResponse.ok) {
      console.log('Error connecting to API. Code: ', loginResponse.status);
      return;
    }
    const userLoginResponse: LoginResponse = await loginResponse.json();

    //Get info about user using ID
    const userInfoResponse = await fetch(`/api/user/${userLoginResponse.id}`, {
      credentials: 'include',
    });
    if (!userInfoResponse.ok) {
      console.log('Error connecting to API. Code: ', userInfoResponse.status);
      return;
    }
    const userResponse: User = await userInfoResponse.json();

    localStorage.setItem('user', JSON.stringify(userResponse));
    setUser(userResponse);
  };

  const logout = async (e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
    e.preventDefault();

    const response = await fetch('api/auth/logout', {
      method: 'POST',
      credentials: 'include',
    });
    if (response.status != 200) {
      console.log('Error logging out. Code: ', response.status);
      return;
    }

    localStorage.removeItem('user');
    setUser(undefined);
  };

  return (
    <div className="flex flex-col">
      <div className="flex flex-row space-x-2 px-3 my-2 justify-end">
        {user ? (
          <>
            <p>Hello {user.name}</p>
            <a
              className="cursor-pointer text-blue-500 underline"
              onClick={logout}>
              Logout
            </a>
          </>
        ) : (
          <GoogleLogin onSuccess={login} />
        )}
      </div>
      <ElementList />
    </div>
  );
}

export default App;
