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

export function ProfilePage() {
  const { user, loading } = useUserProfile();
  const [ updateUser, updateUserMutation ] = useUpdateUserMutation();
  const isLoading = updateUserMutation.loading || loading;

  const onUserChange = (updatedUser: User) => {
    if (user.name !== updatedUser.name) {
      updateUser({ variables: {id: user.id, changes: { name: updatedUser.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>
                <WithLoader loading={isLoading || !user}>
                {
                  <UserForm onChange={onUserChange} user={user} />
                }
                </WithLoader>
              </div>
            </div>
          </div>
        </section>
      </div>
    </Page>
  );
}