import { FC, useState } from 'react';
import { useMutation } from 'react-query';

import DeleteIcon from '@material-hu/icons/material/Delete';
import Box from '@material-hu/mui/Box';
import IconButton from '@material-hu/mui/IconButton';
import Table from '@material-hu/mui/Table';
import TableBody from '@material-hu/mui/TableBody';
import TableCell from '@material-hu/mui/TableCell';
import TableHead from '@material-hu/mui/TableHead';
import TableRow from '@material-hu/mui/TableRow';
import TextField from '@material-hu/mui/TextField';
import Tooltip from '@material-hu/mui/Tooltip';

import Button from '@material-hu/components/design-system/Buttons/Button';
import useSnackbar from '@material-hu/components/design-system/Snackbar';

import useGeneralError from 'src/hooks/useGeneralError';
import { useTranslation } from 'src/pages/dashboard/recognitions/i18n';
import { getUserData } from 'src/services/nemakEvents';
import { EmployeeTableObject } from 'src/types/recognitions';

export type EmployeesTableProps = {
  selectedUsers: EmployeeTableObject[];
  onAddSelectedUsers?: (employee: EmployeeTableObject[]) => void;
  isReadOnly?: boolean;
};

export const EmployeesTable: FC<EmployeesTableProps> = props => {
  const { selectedUsers, onAddSelectedUsers, isReadOnly = false } = props;

  const { t } = useTranslation();
  const { enqueueSnackbar } = useSnackbar();
  const showGeneralError = useGeneralError();

  const [employeeId, setEmployeeId] = useState('');

  const fetchUserData = async id => {
    try {
      const response = await getUserData(id);
      if (response.data.Logger) {
        throw new Error('Invalid Employee');
      }
      return response.data.EmployeeBasics;
    } catch (error) {
      showGeneralError(error, t('ERROR_ADDING_EMPLOYEE_TABLE'));
    }
  };

  const { mutateAsync, isLoading } = useMutation(fetchUserData);

  const createUserObject = userData => ({
    employeeName: `${userData.FirstName} ${userData.LastName}`,
    EmployeeNumber: userData.PersonIdExternal,
    Age: userData.Age,
  });

  const isUserAlreadySelected = (usersList, employeeNumber) =>
    usersList?.some(user => user.EmployeeNumber === employeeNumber);

  const handleAddUser = async () => {
    try {
      const userData = await mutateAsync(employeeId);

      if (!selectedUsers) {
        onAddSelectedUsers([createUserObject(userData)]);
        setEmployeeId('');
        return;
      }

      if (isUserAlreadySelected(selectedUsers, userData.PersonIdExternal)) {
        enqueueSnackbar({ title: t('EXISTS_EMPLOYEE'), variant: 'info' });
      } else {
        onAddSelectedUsers([...selectedUsers, createUserObject(userData)]);
      }

      setEmployeeId('');
    } catch (error) {
      if (error.message === 'Invalid Employee') {
        enqueueSnackbar({ title: t('NOT_EMPLOYEE_FOUND'), variant: 'error' });
      }
    }
  };

  const handleDeleteUser = id => {
    const updatedUsers = selectedUsers.filter(
      user => user.EmployeeNumber !== id,
    );
    onAddSelectedUsers(updatedUsers);
  };

  return (
    <Box sx={{ mt: isReadOnly ? 0 : 2, mb: 2 }}>
      {!isReadOnly && (
        <>
          <TextField
            value={employeeId}
            onChange={e => setEmployeeId(e.target.value)}
            variant="standard"
            placeholder={t('ENTER_EMPLOYEE_ID')}
            sx={{ pl: 2, minWidth: '220px' }}
          />
          <Button
            onClick={handleAddUser}
            sx={{ ml: 1 }}
            disabled={
              isLoading || (selectedUsers && selectedUsers.length === 5)
            }
          >
            {t('ADD_EMPLOYEE')}
          </Button>
        </>
      )}
      {selectedUsers?.length > 0 && (
        <Table sx={{ mb: 2 }}>
          <TableHead>
            <TableRow>
              <TableCell>ID</TableCell>
              <TableCell>{t('NAME_FIELD')}</TableCell>
              {!isReadOnly && <TableCell />}
            </TableRow>
          </TableHead>
          <TableBody>
            {selectedUsers?.map(user => (
              <TableRow key={user.EmployeeNumber}>
                <TableCell>{user.EmployeeNumber}</TableCell>
                <TableCell>{user.employeeName}</TableCell>
                {!isReadOnly && (
                  <TableCell>
                    <Tooltip
                      title={t('DELETE_EMPLOYEE')}
                      placement="top"
                    >
                      <IconButton
                        onClick={() => handleDeleteUser(user.EmployeeNumber)}
                      >
                        <DeleteIcon sx={{ color: 'red' }} />
                      </IconButton>
                    </Tooltip>
                  </TableCell>
                )}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </Box>
  );
};

export default EmployeesTable;
