import React, { FC } from 'react';
import {
  Alert,
  AlertDescription,
  AlertIcon,
  AlertTitle,
  Box,
  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 { landingApi } from '../../__data__/service/landing.api';
import { ErrorMessage } from '../../models/api';
import { FEATURE } from '../../__data__/features';

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

  const { orderId } = useParams<Order.Id>();
  const {
    isLoading,
    isSuccess,
    data: order,
    isError,
    error,
  } = landingApi.useGetOrderQuery(
    {
      orderId,
    },
    FEATURE.orderViewStatusPolling.isOn
      ? {
        pollingInterval: FEATURE.orderViewStatusPolling.getValue(),
        skipPollingIfUnfocused: true,
      }
      : undefined,
  );
  const errorMessage = error as ErrorMessage;

  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
                    orderNumber={order.orderNumber}
                    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' alignItems='flex-start'>
                    <AlertIcon />
                    <Box>
                      <AlertTitle>
                        {t('get-order-query.error.title')}
                      </AlertTitle>
                      <AlertDescription>{errorMessage}</AlertDescription>
                    </Box>
                  </Alert>
                )}
              </>
            </>
          )}
        </VStack>
      </Container>
    </LandingThemeProvider>
  );
};

export default withLandingThemeProvider(Page);
