import React from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { Pane, Heading, toaster } from 'evergreen-ui';
import { useTranslation } from 'react-i18next';

import Config from '../config/config';
import Utils from '../libs/utils';
import apiRouters from '../config/api_routers';

const Signin = (props: RouteComponentProps) => {
  React.useEffect(() => {
    window.addEventListener('message', (event) => {
      const baseUrl = process.env.REACT_APP_CLUSTER_URL as string;
      console.log(event.origin);
      console.log(process.env.REACT_APP_CLUSTER_URL);
      console.log('-----');
      console.log(!event.origin.includes(baseUrl));
      console.log('-----');
      console.log(event.data);
      console.log('-----');
      if (!event.origin.includes(process.env.REACT_APP_CLUSTER_URL!)) return;
      doSignin(event.data);
    });
  }, []);

  const { t } = useTranslation(['signin']);
  const doSignin = (data: Record<string, string>) => {
    Utils.axiosInstance
      .post(Utils.loadUrl(apiRouters.router.sign_in, null), {
        host: data.host,
        port: data.port,
        username: data.username,
        passwd: data.password,
      })
      .then((response) => {
        console.log(response);
        try {
          if (!response.data || response.data.has_error) {
            switch (response.data.message) {
              case 0:
                console.log(t('signin:form_has_error'));
                toaster.danger(t('signin:form_has_error'));
                break;
              case 1:
                console.log(t('signin:form_error_passport'));
                toaster.danger(t('signin:form_error_passport'));
                break;
              case 2:
                console.log(t('signin:form_error_ssh_login'));
                toaster.danger(t('signin:form_error_ssh_login'));
                break;
            }

            if (window && window.parent) {
              console.log('Send Message has error');
              window.parent.postMessage(
                {
                  message: 'close',
                },
                '*',
              );
            }
            props.history.push('/');
          } else {
            if (!response.data.addition) {
              toaster.danger(t('signin:form_error_remote_server'));
              if (window && window.parent) {
                console.log('Send Message Else');
                window.parent.postMessage(
                  {
                    message: 'close',
                  },
                  '*',
                );
              }
              props.history.push('/');
            } else {
              toaster.success(t('signin:signin_success'));
              localStorage.setItem('user.host', data.host);
              localStorage.setItem('user.username', data.username);
              sessionStorage.setItem(
                Config.jwt.tokenName,
                response.data.addition,
              );

              props.history.push('/console');
            }
          }
        } catch (e) {
          console.log(e.message);
          toaster.danger(t('signin:form_error_ssh_login'));
          if (window && window.parent) {
            console.log('Send Message Error 1');
            window.parent.postMessage(
              {
                message: 'close',
              },
              '*',
            );
          }
          props.history.push('/');
        }
      })
      .catch((e: Error) => {
        console.log(e.message);
        toaster.danger(t('signin:form_error_ssh_login') + ': ' + e.message);
        if (window && window.parent) {
          console.log('Send Message Error 2');
          window.parent.postMessage(
            {
              message: 'close',
            },
            '*',
          );
        }
        props.history.push('/');
      });
  };

  return (
    <Pane
      alignItems="center"
      justifyContent="center"
      display="flex"
      flexDirection="column">
      <div
        style={{ minHeight: '360px', marginTop: '10rem', textAlign: 'center' }}>
        <Heading marginBottom="0.6rem" marginTop="0.6rem" size={700}>
          {t('signin:form_title')}
        </Heading>
        <span>Waiting for loging - Test 8</span>!
      </div>
    </Pane>
  );
};

export default Signin;
