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

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 [masters, setMasters] = useState<MasterProps[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const { fetchMasters } = armService();

  useEffect(() => {
    const loadMasters = async () => {
      setLoading(true);

      try {
        const data = await fetchMasters();
        setMasters(data.body);
      } catch (err) {
        setError(err.message);
        toast({
          title: t('error.title'),
          status: 'error',
          duration: 5000,
          isClosable: true,
          position: 'bottom-right',
        });
      } finally {
        setLoading(false);
      }
    };

    loadMasters();
  }, [toast, t]);

  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>
          {loading && (
            <Tr>
              <Td colSpan={TABLE_HEADERS.length} textAlign='center' py='8'>
                <Spinner size='lg' />
              </Td>
            </Tr>
          )}
          {!loading && masters.length === 0 && !error && (
            <Tr>
              <Td colSpan={TABLE_HEADERS.length}>
                <Text>{t('table.empty')}</Text>
              </Td>
            </Tr>
          )}
          {!loading &&
            !error &&
            masters.map((master, index) => (
              <MasterItem key={index} {...master} />
            ))}
        </Tbody>
      </Table>
      <MasterDrawer isOpen={isOpen} onClose={onClose} />
    </Box>
  );
};

export default Masters;
