import { useEffect, useState } from 'react';
import Modal from '../../../components/common/Modal/Modal';
import { Box, Typography } from '@mui/material';
import InlineTagInput from '../../../components/common/InlineTagInput';
import styled from '@emotion/styled';
import { toast } from 'react-toastify';
import { UsersApi } from '../../../api/users';
import { EmptyListIcon } from '../../../components/common/icons/icons';
import { TrashSvg } from '../../../components/common/icons/icons';
import {
  PrimaryButton,
  SecondaryButton,
} from '../../../components/common/Buttons/Buttons';

const ContainerForEmptyIcon = styled(Box)`
  height: 22.88rem;
  width: 58.13rem;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  justify-content: center;
  align-items: center;
`;

export const ModalAddUsers = ({ open, onClose, onAddUser }) => {
  const [users, setUsers] = useState([]);
  const [tableIsEmpty, setTableEmpty] = useState(true);
  const [usersEmailToAdd, setUsersToAdd] = useState([]);

  const handleAddToListUser = (users) => {
    setUsers(users);
    setTableEmpty(false);
  };

  useEffect(() => {
    setUsers([]);
    setTableEmpty(true);
    setUsersToAdd([]);
  }, [open]);

  useEffect(() => {
    const newUsers = users.map((u) => ({
      full_name: '',
      email: u,
      username: u.split('@')[0],
    }));
    setUsersToAdd((prev) => [...prev, ...newUsers]);
  }, [users]);

  const handleDeleteUser = (indx) => {
    setUsersToAdd((prev) => {
      return prev.filter((item, i) => i !== indx);
    });
  };

  const handleAddUsers = () => {
    for (const user of usersEmailToAdd) {
      user['password'] = 'admin123';
      UsersApi.createUser(user)
        .then((data) => {
          if (data.success) {
            onAddUser(data.result);
          } else {
            toast.error(
              'При добавлении пользователя возникла ошибка: ',
              data.message,
            );
          }
        })
        .catch((error) => {
          toast.error('При добавлении пользователя возникла ошибка: ');
        });
    }
    onClose?.();
  };
  return (
    <Modal
      title={'Добавить пользователей'}
      open={open}
      onClose={onClose}
      customSize={58.13}
      actions={
        <>
          <SecondaryButton onClick={onClose} height={'2.5rem'}>
            Отменить
          </SecondaryButton>
          <PrimaryButton height={'2.5rem'} onClick={handleAddUsers}>
            Сохранить
          </PrimaryButton>
        </>
      }
    >
      <InlineTagInput onSaveTags={handleAddToListUser}></InlineTagInput>
      {users.length == 0 && tableIsEmpty ? (
        <ContainerForEmptyIcon>
          <EmptyListIcon />
          <Typography
            sx={{
              fontWeight: 400,
              fontSize: '0.88rem',
              color: '#323031',
            }}
          >
            Список пользователей пуст
          </Typography>
        </ContainerForEmptyIcon>
      ) : (
        <Box
          sx={{
            paddingTop: '1.25rem',
            display: 'grid',
            gridTemplateRows: 'auto 1fr',
            width: '55.13rem',
            height: '22.88rem',
            overflow: 'hidden',
          }}
        >
          <Box
            sx={{
              display: 'grid',
              gridTemplateColumns: '29.75rem 21.38rem 4rem',
              gap: '0.75rem',
              position: 'sticky',
              top: 0,
              zIndex: 1,
              borderBottom: '1px solid #ccc',
              paddingBottom: '.5rem',
            }}
          >
            <Box
              sx={{ fontSize: '0.75rem', lineHeight: '133%', color: '#323031' }}
            >
              ФИО
            </Box>
            <Box
              sx={{ fontSize: '0.75rem', lineHeight: '133%', color: '#323031' }}
            >
              Почта
            </Box>
            <Box></Box>
          </Box>

          <Box
            sx={{
              overflowY: 'auto',
              paddingTop: '.38rem',
            }}
          >
            <Box
              sx={{
                display: 'grid',
                gridTemplateColumns: '29.75rem 21.38rem 4rem',
                gap: '0.75rem',
                width: '100%',
              }}
            >
              {usersEmailToAdd.map((user, index) => (
                <Box
                  key={user.email}
                  sx={{
                    display: 'contents',
                  }}
                >
                  <Box>
                    <input
                      type="text"
                      defaultValue={user.full_name}
                      onChange={(event) => {
                        user.full_name = event.target.value;
                      }}
                      style={{
                        border: '1px solid #ccc',
                        borderRadius: '0.5rem',
                        fontSize: '0.75rem',
                        boxSizing: 'border-box',
                        width: '20.5rem',
                        height: '2rem',
                        padding: '0.25rem 0.75rem',
                        color: '#4a5565',
                      }}
                    />
                  </Box>

                  <Box
                    sx={{
                      border: '1px solid #ccc',
                      borderRadius: '0.5rem',
                      fontSize: '0.75rem',
                      boxSizing: 'border-box',
                      height: '2rem',
                      padding: '0.25rem 0.75rem',
                      color: '#4a5565',
                      width: 'min-content',
                      maxWidth: '100%',
                      backgroundColor: 'white',
                    }}
                  >
                    {user.email}
                  </Box>

                  <Box sx={{ textAlign: 'center' }}>
                    <button
                      onClick={() => handleDeleteUser(index)}
                      style={{
                        width: '2rem',
                        height: '2rem',
                        border: 'none',
                      }}
                    >
                      <TrashSvg size={'1.25rem'} fill={'#ff6467'} />
                    </button>
                  </Box>
                </Box>
              ))}
            </Box>
          </Box>
        </Box>
      )}
    </Modal>
  );
};
