import React from 'react';
import { Page } from '../Page';
import { UserForm } from '../UserForm';
import { User } from '../../types/user';
import { useUserProfile } from '../../gql/queries/profile';
import { useUpdateUserProfileMutation } from '../../gql/mutations/profile';

export function ProfilePage() {
  const { user, loading } = useUserProfile();
  const [ updateProfile, updateUserProfileMutation ] = useUpdateUserProfileMutation();
  const isLoading = updateUserProfileMutation.loading || loading;

  const onUserChange = (user: User) => {
    if (user.name !== user.name) {
      updateProfile({ 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">
              <div className="box">
                <h2 className="is-size-2 subtitle">Mon profil</h2>
                { !isLoading ? <UserForm onChange={onUserChange} user={user} /> : null }
              </div>
            </div>
          </div>
        </section>
      </div>
    </Page>
  );
}

export default ProfilePage;