import { Container, Box, Alert, AlertIcon } from '@chakra-ui/react';
import { useRef } from 'react';
import { useMutation, useQueryClient } from 'react-query';
import { useNavigate } from 'react-router-dom';
import { useMyToast } from '../../hooks';
import { ROUTES } from '../../constants/paths';
import { Breadcrumb } from '../../components/common';
import JobCreationForm from '../../components/jobs/JobCreationForm';
import { EVENT_NAMES, STATUS_MESSAGES } from '../../constants/define';

const JobCreationPage = () => {
  const navigate = useNavigate(),
    toast = useMyToast(),
    formikRef = useRef(),
    breadcrumbItems = [
      {
        title: 'Jobs',
        href: ROUTES.DASHBOARD.JOBS.ROOT.path,
      },
      {
        title: 'Create Job',
        isCurrentPage: true,
      },
    ],
    queryClient = useQueryClient();

  const { mutate, isLoading, error, isError } = useMutation({
    mutationKey: [EVENT_NAMES.JOBS.CREATE],
    mutationFn: () => {
      const values = formikRef.current.values;
      console.log(values);
      return window.grpcAPIs[EVENT_NAMES.JOBS.CREATE](values);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [EVENT_NAMES.JOBS.LIST],
      });
      toast({
        title: 'Success',
        description: STATUS_MESSAGES.CREATE_SUCCESS,
        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">
        <JobCreationForm formRef={formikRef} isLoading={isLoading} onCreate={mutate} />
      </Box>
    </Container>
  );
};

export default JobCreationPage;
