import { useQuery, useMutation } from '@apollo/client';
import { USER_PROFILE, UPDATE_PROFILE } from './schema';
import {
  UpdateProfileMutation,
  UpdateProfileMutationVariables,
  UserProfileQuery,
} from 'types/graphql';

import { ProfileDataForm, ProfileFormValues } from './ProfileDataForm';
import { Button, Spinner } from 'components/common';
import { ErrorScreen } from 'components/ErrorScreen';
import { ErrorBoundary } from 'components/ErrorBoundary';

export const ProfileScreen = () => {
  const { data, loading, error, refetch } =
    useQuery<UserProfileQuery>(USER_PROFILE);
  const [submit, { loading: mutationLoading }] = useMutation<
    UpdateProfileMutation,
    UpdateProfileMutationVariables
  >(UPDATE_PROFILE);

  const handleSubmit = (data: ProfileFormValues) => {
    const { companyName, firstName, lastName } = data;
    submit({
      variables: {
        input: {
          companyName,
          firstName,
          lastName,
        },
      },
    });
  };

  return (
    <ErrorBoundary>
      {data && (
        <ProfileDataForm
          initialState={data.user ? data.user : undefined}
          onSubmit={handleSubmit}
          loading={mutationLoading}
        />
      )}
      {error && (
        <ErrorScreen message={error.message}>
          <Button onClick={() => refetch()}>Try again</Button>
        </ErrorScreen>
      )}
      <Spinner show={loading || mutationLoading} />
    </ErrorBoundary>
  );
};
