import React, { useEffect, useState } from 'react';
import {
  Box,
  Heading,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Spinner,
  Text,
  Td,
  useToast,
} from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';

import OrderItem from '../OrderItem';
import { OrderProps } from '../OrderItem/OrderItem';
import DateNavigator from '../DateNavigator';
import {
  useGetMastersQuery,
  useGetOrdersQuery,
} from '../../__data__/service/api';

const TABLE_HEADERS = [
  'carNumber' as const,
  'orderDate' as const,
  'status' as const,
  'masters' as const,
  'telephone' as const,
  'location' as const,
];

const Orders = () => {
  const { t } = useTranslation('~', {
    keyPrefix: 'dry-wash.arm.order',
  });
  const toast = useToast();

  const [currentDate, setCurrentDate] = useState(new Date());
  const {
    data: orders,
    isLoading: isOrdersLoading,
    isSuccess: isOrdersSuccess,
    isError: isOrdersError,
    error: ordersError,
  } = useGetOrdersQuery({ date: currentDate });

  const {
    data: masters,
    isLoading: isMastersLoading,
    isSuccess: isMastersSuccess,
    isError: isMastersError,
    error: mastersError,
  } = useGetMastersQuery();

  const isLoading = isOrdersLoading || isMastersLoading;
  const isSuccess = isOrdersSuccess && isMastersSuccess;
  const isError = isOrdersError || isMastersError;

  useEffect(() => {
    if (isError) {
      toast({
        title: t('error.title'),
        // description: errorMessage,
        status: 'error',
        duration: 5000,
        isClosable: true,
        position: 'bottom-right',
      });
    }
  }, [isError, ordersError, mastersError, toast, t]);

  return (
    <Box p='8'>
      <Heading size='lg' mb='5'>
        {t('title')}
      </Heading>

      <DateNavigator
        currentDate={currentDate}
        onPreviousDate={() =>
          setCurrentDate((prevDate) =>
            dayjs(prevDate).subtract(1, 'day').toDate(),
          )
        }
        onNextDate={() =>
          setCurrentDate((prevDate) => dayjs(prevDate).add(1, 'day').toDate())
        }
      />

      <Table variant='simple' colorScheme='blackAlpha'>
        <Thead>
          <Tr>
            {TABLE_HEADERS.map((name, key) => (
              <Th key={key}>{t(`table.header.${name}`)}</Th>
            ))}
          </Tr>
        </Thead>
        <Tbody>
          {isLoading && (
            <Tr>
              <Td colSpan={TABLE_HEADERS.length} textAlign='center' py='8'>
                <Spinner size='lg' />
              </Td>
            </Tr>
          )}
          {isSuccess && orders.length === 0 && (
            <Tr>
              <Td colSpan={TABLE_HEADERS.length}>
                <Text>{t('table.empty')}</Text>
              </Td>
            </Tr>
          )}
          {isSuccess &&
            orders.map((order, index) => (
              <OrderItem
                allMasters={masters}
                key={index}
                {...order}
                status={order.status as OrderProps['status']}
              />
            ))}
        </Tbody>
      </Table>
    </Box>
  );
};

export default Orders;
