import React, { FC } from 'react';
import { Alert, AlertDescription, AlertIcon, AlertTitle, HStack, Spinner } from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
import { Container, Heading, VStack } from '@chakra-ui/react';
import { useParams } from 'react-router-dom';

import {
  LandingThemeProvider,
  withLandingThemeProvider,
} from '../../containers';
import { OrderDetails } from '../../components/order-view';
import { Order } from '../../models/landing';
import { useGetOrderQuery } from '../../api';

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

  const { orderId } = useParams<Order.Id>();
  const {
    isLoading,
    isSuccess,
    data: { body: order } = {},
    isError,
    error,
  } = useGetOrderQuery({
    orderId,
  });

  return (
    <LandingThemeProvider>
      <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>
          {isLoading ? (
            <HStack width='full' justifyContent='center'>
              <Spinner size='lg' />
            </HStack>
          ) : (
            <>
              <>
                {isSuccess && (
                  <OrderDetails
                    id={order.id}
                    status={order.status}
                    phone={order.phone}
                    carNumber={order.carNumber}
                    carBody={order.carBody}
                    carColor={order.carColor}
                    location={order.location}
                    startWashTime={order.startWashTime}
                    endWashTime={order.endWashTime}
                    created={order.created}
                  />
                )}
              </>
              <>
                {isError && (
                  <Alert status='error'>
                    <AlertIcon />
                    <AlertTitle>
                      {t('get-order-query.error.title', {
                        number: orderId,
                      })}
                    </AlertTitle>
                    <AlertDescription>{error.data?.error}</AlertDescription>
                  </Alert>
                )}
              </>
            </>
          )}
        </VStack>
      </Container>
    </LandingThemeProvider>
  );
};

export default withLandingThemeProvider(Page);
