import React, { useState } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import {
  //Button,
  Pane,
  Heading,
  //TextInputField,
  //GeolocationIcon,
  //FormField,
  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';

{
  /*interface FieldState {
  isInvalid: boolean;
  validationMessage: string | undefined;
  value: string;
}

const checkHostFormat = (host: string) => {
  if (!host || host === '') {
    return [false, '', 22];
  }
  const hostList = host.split(':');
  if (hostList.length === 1) {
    return [true, host, 22];
  }
  const ok =
    hostList.length === 2 &&
    hostList[1].length !== 0 &&
    !isNaN(Number(hostList[1]));
  if (ok) {
    return [true, hostList[0], parseInt(hostList[1])];
  } else {
    return [false, host, 22];
  }
};*/
}
const Signin = (props: RouteComponentProps) => {
  React.useEffect(() => {
    window.addEventListener('message', (event) => {
      if (event.origin !== process.env.REACT_APP_CLUSTER_URL) return;

      doSignin(event.data);
    });
  }, []);

  const { t } = useTranslation(['signin']);

  const doSignin = (data: Record<string, string>) => {
    console.log(data);
    Utils.axiosInstance
      .post(Utils.loadUrl(apiRouters.router.sign_in, null), {
        // _xsrf: Utils.base64Decode(xsrf.split("|")[0]), // todo
        host: data.host,
        port: data.port,
        username: data.username,
        passwd: data.password,
      })
      .then((response) => {
        try {
          if (!response.data || response.data.has_error) {
            // self.$Loading.error();
            switch (response.data.message) {
              case 0:
                toaster.danger(t('signin:form_has_error'));
                break;
              case 1:
                toaster.danger(t('signin:form_error_passport'));
                break;
              case 2:
                toaster.danger(t('signin:form_error_ssh_login'));
                break;
            }
          } else {
            if (!response.data.addition) {
              // self.$Loading.error();
              toaster.danger(t('signin:form_error_remote_server'));
            } else {
              // self.$Loading.finish();
              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) {
          // self.$Loading.error();
          toaster.danger(t('signin:form_error_ssh_login'));
        }
      })
      .catch((e: Error) => {
        // self.$Loading.error();
        toaster.danger(t('signin:form_error_ssh_login') + ': ' + e.message);
      });
  };

  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>
        {/*
        <form
          onSubmit={(event: React.FormEvent<HTMLFormElement>) => {
            event.preventDefault();
            doSignin();
            return false;
          }}>
          <Pane textAlign="left">
            <TextInputField
              value={hostField.value}
              isInvalid={hostField.isInvalid}
              validationMessage={hostField.validationMessage}
              label={t('signin:form_fullhost_label')}
              onChange={onHostChanged}
              onBlur={onHostChanged}
              placeholder={t('signin:form_fullhost_ph')}
              marginBottom="8px"
            />
            <TextInputField
              value={unameField.value}
              isInvalid={unameField.isInvalid}
              label={t('signin:form_username_label')}
              onChange={onUsernameChanged}
              onBlur={onUsernameChanged}
              placeholder={t('signin:form_username_ph')}
              validationMessage={unameField.validationMessage}
              marginBottom="8px"
            />
            <TextInputField
              label={t('signin:form_passwd_label')}
              type="password"
              placeholder={t('signin:form_passwd_ph')}
              marginBottom="24px"
              onChange={onPasswdChanged}
              onBlur={onPasswdChanged}
              onKeyDown={(event: React.KeyboardEvent<HTMLDivElement>): void => {
                // 'keypress' event misbehaves on mobile so we track 'Enter' key via 'keydown' event
                if (event.key === 'Enter') {
                  event.preventDefault();
                  event.stopPropagation();
                  doSignin();
                }
              }}
            />
          </Pane>
          <FormField>
            <Button
              isLoading={submitLoading}
              type="submit"
              width="100%"
              appearance="primary"
              justifyContent="center"
              intent="success"
              iconBefore={GeolocationIcon}>
              {t('signin:form_submit_btn')}
            </Button>
          </FormField>
        </form>
        */}
      </div>
    </Pane>
  );
};

export default Signin;
