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

import CloseIcon from '@material-hu/icons/material/Close';
import Visibility from '@material-hu/icons/material/Visibility';
import VisibilityOff from '@material-hu/icons/material/VisibilityOff';
import Alert from '@material-hu/mui/Alert';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Dialog from '@material-hu/mui/Dialog';
import DialogActions from '@material-hu/mui/DialogActions';
import DialogContent from '@material-hu/mui/DialogContent';
import DialogContentText from '@material-hu/mui/DialogContentText';
import DialogTitle from '@material-hu/mui/DialogTitle';
import IconButton from '@material-hu/mui/IconButton';
import InputAdornment from '@material-hu/mui/InputAdornment';
import Stack from '@material-hu/mui/Stack';
import TextField from '@material-hu/mui/TextField';

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

import useGeneralError from 'src/hooks/useGeneralError';
import { useTranslation } from 'src/pages/dashboard/recognitions/i18n';
import { recognitionsRoutes } from 'src/pages/dashboard/recognitions/routes';
import { loginUser } from 'src/services/recognitions';
import { Credentials } from 'src/types/recognitions';

export type CredentialsDialogProps = {
  open: boolean;
  onClose: () => void;
  onLoggedUser: () => void;
};

export const CredentialsDialog: FC<CredentialsDialogProps> = props => {
  const { open, onClose, onLoggedUser } = props;

  const { t } = useTranslation();
  const navigate = useNavigate();
  const showGeneralError = useGeneralError();

  const [employeeId, setEmployeeId] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showErrorMessage, setShowErrorMessage] = useState(false);

  const { mutate: fetchUserData, isLoading } = useMutation(
    (credentials: Credentials) =>
      loginUser(credentials.id, credentials.password),
    {
      onSuccess: (data, variables) => {
        if (data?.data.StatusCode === '0') {
          setShowErrorMessage(false);
          localStorage.setItem('userId', variables.id);
          onLoggedUser();
          navigate(recognitionsRoutes.home());
        } else {
          setShowErrorMessage(true);
        }
      },
      onError: error => {
        showGeneralError(error, t('ERROR_LOGIN'));
      },
    },
  );

  const handleButtonClick = (id: string) => fetchUserData({ id, password });

  return (
    <Dialog
      open={open}
      onClose={onClose}
    >
      <DialogTitle sx={{ display: 'flex', justifyContent: 'space-between' }}>
        {t('EMPLOYEE_CREDENTIALS')}
        <IconButton onClick={onClose}>
          <CloseIcon fontSize="small" />
        </IconButton>
      </DialogTitle>
      <DialogContent sx={{ pb: 1.6 }}>
        <DialogContentText>
          {t('CREDENTIALS_DIALOG_DESCRIPTION')}
        </DialogContentText>
        <TextField
          autoFocus
          margin="dense"
          id="name"
          label={t('MEMBERSHIP_NUMBER')}
          fullWidth
          variant="standard"
          onChange={event => setEmployeeId(event.target.value)}
        />
        <TextField
          autoFocus
          margin="dense"
          id="name"
          label={t('PASSWORD')}
          type={showPassword ? 'text' : 'password'}
          fullWidth
          variant="standard"
          onChange={event => setPassword(event.target.value)}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton
                  edge="end"
                  onClick={() => setShowPassword(!showPassword)}
                >
                  {showPassword ? <Visibility /> : <VisibilityOff />}
                </IconButton>
              </InputAdornment>
            ),
          }}
        />
        {showErrorMessage && (
          <Stack
            sx={{
              width: '100%',
              mt: 2,
            }}
          >
            <Alert
              sx={{ borderRadius: '6px' }}
              severity="error"
            >
              {t('INVALID_CREDENTIALS')}
            </Alert>
          </Stack>
        )}
      </DialogContent>
      <DialogActions>
        <Button
          disabled={isLoading || !employeeId.trim() || !password.trim()}
          onClick={() => handleButtonClick(employeeId)}
          sx={{ display: 'flex', alignItems: 'center' }}
        >
          {isLoading && (
            <CircularProgress
              size={20}
              sx={{ mr: 0.6 }}
            />
          )}
          {t('START_REGISTRATION')}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default CredentialsDialog;
