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

import MasterItem from '../MasterItem';
import MasterDrawer from '../MasterDrawer';
import { api } from '../../__data__/service/api';

const TABLE_HEADERS = [
  'name' as const,
  'currentJob' as const,
  'phone' as const,
  'actions' as const,
];

const Masters = () => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const toast = useToast();
  const { t } = useTranslation('~', {
    keyPrefix: 'dry-wash.arm.master',
  });

  const {
    data: masters,
    error,
    isLoading,
    isSuccess,
  } = api.useGetMastersQuery();

  useEffect(() => {
    if (error) {
      toast({
        title: t('error.title'),
        status: 'error',
        isClosable: true,
        position: 'bottom-right',
      });
    }
  }, [error]);

  return (
    <Box p='8'>
      <Flex justifyContent='space-between' alignItems='center' mb='5'>
        <Heading size='lg'> {t('title')}</Heading>
        <Button colorScheme='green' onClick={onOpen}>
          + {t('add')}
        </Button>
      </Flex>
      <Table variant='simple' colorScheme='blackAlpha'>
        <Thead>
          <Tr>
            {TABLE_HEADERS.map((name) => (
              <Th key={name}>{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 && masters.length === 0 && (
            <Tr>
              <Td colSpan={TABLE_HEADERS.length}>
                <Text>{t('table.empty')}</Text>
              </Td>
            </Tr>
          )}
          {isSuccess &&
            masters.map((master, index) => (
              <MasterItem key={index} {...master} />
            ))}
        </Tbody>
      </Table>
      <MasterDrawer isOpen={isOpen} onClose={onClose} />
    </Box>
  );
};

export default Masters;
