import { useRef } from 'react';
import { Container, Box, Alert, AlertIcon } from '@chakra-ui/react';
import { useMutation, useQuery, useQueryClient } from 'react-query';
import { useParams } from 'react-router-dom';

import { useMyToast } from '../../hooks';
import { ROUTES } from '../../constants/paths';
import { Breadcrumb } from '../../components/common';
import { UserUpdationForm } from '../../components/users';
import { getDiff } from '../../utilities/functions';
import { EVENT_NAMES, STATUS_MESSAGES, TIME_INTERVALS } from '../../constants/define';

function UserUpdationPage() {
  const { userId } = useParams(),
    toast = useMyToast(),
    formikRef = useRef(),
    queryClient = useQueryClient();

  const { data } = useQuery({
    queryKey: [EVENT_NAMES.USERS.VIEW, userId],
    queryFn: () => {
      return window.grpcAPIs[EVENT_NAMES.USERS.VIEW](userId);
    },
    initialData: () => queryClient.getQueryData([EVENT_NAMES.USERS.VIEW, userId]),
    staleTime: TIME_INTERVALS.TEN_MINUTES_IN_MILLISECONDS,
    initialDataUpdatedAt: () => queryClient.getQueryState([EVENT_NAMES.USERS.VIEW, userId])?.dataUpdatedAt,
  });

  const breadcrumbItems = [
    {
      title: 'Users',
      href: ROUTES.DASHBOARD.USERS.ROOT.path,
    },
    {
      title: data?.email || '',
      isCurrentPage: true,
    },
  ];

  const { mutate, isLoading, error, isError } = useMutation({
    mutationKey: [EVENT_NAMES.USERS.UPDATE, userId],
    mutationFn: () => {
      const values = formikRef.current.values;
      const initialValues = formikRef.current.initialValues;
      const diffValues = getDiff(values, initialValues);
      return window.grpcAPIs[EVENT_NAMES.USERS.UPDATE]({ id: userId, ...diffValues });
    },
    onSuccess: (newData) => {
      formikRef.current.resetForm({
        values: newData,
      });
      queryClient.setQueryData([EVENT_NAMES.USERS.VIEW, userId], newData);
      queryClient.invalidateQueries({
        queryKey: [EVENT_NAMES.USERS.LIST],
      });
      toast({
        title: 'Success',
        description: STATUS_MESSAGES.UPDATE_SUCCESS,
        status: 'success',
      });
    },
  });

  return (
    <Container display="flex" flexDir="column" maxWidth="container.xl" gap={4}>
      <Breadcrumb breadcrumbItems={breadcrumbItems} fontSize="lg" />
      {isError && (
        <Alert status="error">
          <AlertIcon />
          {error?.message}
        </Alert>
      )}
      <Box rounded="lg">
        {data && <UserUpdationForm data={data} formRef={formikRef} isLoading={isLoading} onUpdate={mutate} />}
      </Box>
    </Container>
  );
}

UserUpdationPage.propTypes = {};

export default UserUpdationPage;
