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

import { useMyToast } from '../../hooks';
import { Breadcrumb } from '../../components/common';
import { ROUTES } from '../../constants/paths';
import { EVENT_NAMES } from '../../constants/define';
import UserCreationForm from '../../components/users/UserCreationForm';

function UserCreationPage() {
  const navigate = useNavigate(),
    toast = useMyToast(),
    formikRef = useRef(),
    queryClient = useQueryClient(),
    breadcrumbItems = [
      {
        title: 'Users',
        href: ROUTES.DASHBOARD.USERS.ROOT.path,
      },
      {
        title: 'Create User',
        isCurrentPage: true,
      },
    ];

  const { mutate, isLoading, error, isError } = useMutation({
    mutationKey: [EVENT_NAMES.USERS.CREATE],
    mutationFn: () => {
      const values = formikRef.current.values;
      return window.grpcAPIs[EVENT_NAMES.USERS.CREATE](values);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [EVENT_NAMES.USERS.LIST],
      });
      toast({
        title: 'Success',
        description: 'User created successfully',
        status: 'success',
      });
      navigate(-1);
    },
  });

  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">
        <UserCreationForm formRef={formikRef} isLoading={isLoading} onCreate={mutate} />
      </Box>
    </Container>
  );
}

export default UserCreationPage;
