import React, { useEffect } from 'react';
import { Page } from '../Page';
import { UserForm } from '../UserForm';
import { Loader } from '../Loader';
import { User } from '../../types/user';
import { useUserProfileQuery } from '../../gql/queries/profile';
import { useUpdateUserProfileMutation } from '../../gql/mutations/profile';
import { WithLoader } from '../WithLoader';

export function ProfilePage() {
  const userProfileQuery = useUserProfileQuery();
  const [ updatProfile, updateUserProfileMutation ] = useUpdateUserProfileMutation();
  const isLoading = updateUserProfileMutation.loading || userProfileQuery.loading;

  const { userProfile } = (userProfileQuery.data || {});

  const onUserChange = (user: User) => {
    if (userProfile.name !== user.name) {
      updatProfile({ variables: {changes: { name: user.name }}});
    }
  };

  return (
    <Page title="Mon profil">
      <div className="container is-fluid">
        <section className="section">
          <div className="columns">
            <div className="column is-6 is-offset-3">
              <h2 className="is-size-2 subtitle">Mon profil</h2>
              <WithLoader loading={isLoading}>
              {
                userProfile ?
                <UserForm onChange={onUserChange} user={userProfile} /> :
                <Loader />
              }
              </WithLoader>
            </div>
          </div>
        </section>
      </div>
    </Page>
  );
}