import { useMutation, useQueryClient } from 'react-query';
import { Container, Flex } from '@chakra-ui/react';
import { useRef } from 'react';

import { EVENT_NAMES, STATUS_MESSAGES } from '../../constants/define';
import { ProfileForm } from '../../components/profile';
import { Breadcrumb, AvatarUpload } from '../../components/common';
import { getDiff } from '../../utilities/functions';
import { useMyToast } from '../../hooks';

const Profile = () => {
  const queryClient = useQueryClient(),
    me = queryClient.getQueryData([EVENT_NAMES.ESSENTIAL.RETRIEVE])?.me,
    formikRef = useRef(),
    toast = useMyToast(),
    breadcrumbItems = [
      {
        title: 'Profile',
        isCurrentPage: true,
      },
    ];

  const { mutate, isLoading, error, isError } = useMutation({
    mutationKey: [EVENT_NAMES.USERS.UPDATE, me?.id],
    mutationFn: () => {
      const values = formikRef.current.values;
      const initialValues = formikRef.current.initialValues;
      const diffValues = getDiff(values, initialValues);
      return window.grpcAPIs[EVENT_NAMES.USERS.UPDATE]({ id: me?.id, ...diffValues });
    },
    onSuccess: (newData) => {
      formikRef.current.resetForm({
        values: newData,
      });
      queryClient.setQueryData([EVENT_NAMES.USERS.VIEW, me?.id], newData);
      queryClient.invalidateQueries({
        queryKey: [EVENT_NAMES.ESSENTIAL.RETRIEVE],
      });
    },
    onError: (error) => {
      toast({
        title: 'Error',
        description: error?.message || STATUS_MESSAGES.UPDATE_ERROR,
        status: 'error',
        isClosable: true,
      });
    },
  });

  return (
    <Container maxW="-moz-fit-content" my="1rem">
      <Breadcrumb fontSize="lg" breadcrumbItems={breadcrumbItems} />
      {isError && (
        <Flex justifyContent="center" alignItems="center" height="100vh">
          {error?.message || STATUS_MESSAGES.UPDATE_FAILED}
        </Flex>
      )}
      <Flex>
        <ProfileForm flex="3" onUpdate={mutate} isLoading={isLoading} formRef={formikRef} me={me} />
        <AvatarUpload flex="1" me={me} />
      </Flex>
    </Container>
  );
};

export default Profile;
