import React, { FC } from 'react';
import { useTranslation } from 'react-i18next';
import { Container, Heading, useToast, VStack } from '@chakra-ui/react';
import { useNavigate } from 'react-router-dom';

import { withLandingThemeProvider } from '../../containers';
import { OrderForm, OrderFormProps } from '../../components/order-form';
import { useCreateOrderMutation } from '../../api';
import { URLs } from '../../__data__/urls';

import { formatFormValues } from './helper';

const Page: FC = () => {
  const { t } = useTranslation('~', {
    keyPrefix: 'dry-wash.order-create',
  });

  const [createOrder, createOrderMutation] = useCreateOrderMutation();

  const toast = useToast();
  const navigate = useNavigate();

  const onOrderFormSubmit: OrderFormProps['onSubmit'] = (values) => {
    createOrder({ body: formatFormValues(values) })
      .then(({ body: { id: orderId } }) => {
        navigate({ pathname: URLs.orderView.getUrl(orderId) });
        toast({
          status: 'success',
          title: t('create-order-query.success.title'),
        });
      })
      .catch(({ error: errorMessage }) => {
        toast({
          status: 'error',
          title: t('create-order-query.error.title'),
          description: errorMessage,
        });
      });
  };

  return (
    <Container
      w='full'
      maxWidth='container.xl'
      minH='100vh'
      padding={0}
      bg='white'
      centerContent
    >
      <VStack w='full' h='full' alignItems='stretch' flexGrow={1}>
        <Heading textAlign='center' mt={4}>
          {t('title')}
        </Heading>
        <OrderForm
          onSubmit={onOrderFormSubmit}
          loading={createOrderMutation.isLoading}
        />
      </VStack>
    </Container>
  );
};

export default withLandingThemeProvider(Page);
