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

import OrderItem from '../OrderItem';
import DateNavigator from '../DateNavigator';
import {
  useGetMastersQuery,
  useGetOrdersQuery,
} from '../../__data__/service/api';
import useShowToast from '../../hooks/useShowToast';
import { OrderArm } from '../../models/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 showToast = useShowToast();

  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) {
      showToast(t('error.title'), 'error');
    }
  }, [isError, ordersError, mastersError, 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 OrderArm['status']}
              />
            ))}
        </Tbody>
      </Table>
    </Box>
  );
};

export default Orders;
