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 { armService } from '../../api/arm';
import DateNavigator from '../DateNavigator';
import { MasterProps } from '../MasterItem/MasterItem';

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 { fetchOrders } = armService();
  const { fetchMasters } = armService();

  const toast = useToast();

  const [orders, setOrders] = useState<OrderProps[]>([]);
  const [allMasters, setAllMasters] = useState<MasterProps[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [currentDate, setCurrentDate] = useState(new Date());

  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      setError(null);

      try {
        const [ordersData, mastersData] = await Promise.all([
          fetchOrders({ date: currentDate }),
          fetchMasters(),
        ]);

        setOrders(ordersData.body);
        setAllMasters(mastersData.body);
      } catch (err) {
        setError(err.message);
        toast({
          title: t('error.title'),
          status: 'error',
          duration: 5000,
          isClosable: true,
          position: 'bottom-right',
        });
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [currentDate, 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>
          {loading && (
            <Tr>
              <Td colSpan={TABLE_HEADERS.length} textAlign='center' py='8'>
                <Spinner size='lg' />
              </Td>
            </Tr>
          )}
          {!loading && orders.length === 0 && !error && (
            <Tr>
              <Td colSpan={TABLE_HEADERS.length}>
                <Text>{t('table.empty')}</Text>
              </Td>
            </Tr>
          )}
          {!loading &&
            !error &&
            orders.map((order, index) => (
              <OrderItem
                allMasters={allMasters}
                key={index}
                {...order}
                status={order.status as OrderProps['status']}
              />
            ))}
        </Tbody>
      </Table>
    </Box>
  );
};

export default Orders;
