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(() => {
    const handleMessage = (event: MessageEvent) => {
      if (!event.data || typeof event.data !== 'object') {
        return;
      }

      const clusterUrl = process.env.REACT_APP_CLUSTER_URL;

      if (!clusterUrl) {
        return;
      }

      const normalizeOrigin = (url: string) => {
        try {
          if (url.includes('://')) {
            const urlObj = new URL(url);
            return urlObj.hostname.toLowerCase();
          }
          return url
            .toLowerCase()
            .replace(/^https?:\/\//, '')
            .replace(/:\d+$/, '')
            .split('/')[0]
            .trim();
        } catch {
          return url
            .toLowerCase()
            .replace(/^https?:\/\//, '')
            .replace(/:\d+$/, '')
            .split('/')[0]
            .trim();
        }
      };

      const originHostname = normalizeOrigin(event.origin);
      const clusterHostname = normalizeOrigin(clusterUrl);

      if (originHostname !== clusterHostname) {
        return;
      }

      if (event.data.host && event.data.username && event.data.password) {
        doSignin(event.data);
      }
    };

    window.addEventListener('message', handleMessage);

    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, []);

  const { t } = useTranslation(['signin']);
  const doSignin = (data: Record<string, string>) => {
    const normalizedData = {
      host: String(data.host || '')
        .toLowerCase()
        .trim(),
      port: String(data.port || '22').trim(),
      username: String(data.username || '').trim(),
      passwd: String(data.password || '').trim(),
    };

    if (
      !normalizedData.host ||
      !normalizedData.username ||
      !normalizedData.passwd
    ) {
      console.error('Signin.tsx - Missing required fields:', normalizedData);
      toaster.danger(t('signin:form_has_error'));
      return;
    }

    Utils.axiosInstance
      .post(Utils.loadUrl(apiRouters.router.sign_in, null), {
        host: normalizedData.host,
        port: normalizedData.port,
        username: normalizedData.username,
        passwd: normalizedData.passwd,
      })
      .then((response) => {
        try {
          if (!response.data || response.data.has_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;
            }

            if (window && window.parent) {
              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) {
                window.parent.postMessage(
                  {
                    message: 'close',
                  },
                  '*',
                );
              }
              props.history.push('/');
            } else {
              toaster.success(t('signin:signin_success'));
              localStorage.setItem('user.host', normalizedData.host);
              localStorage.setItem('user.username', normalizedData.username);
              sessionStorage.setItem(
                Config.jwt.tokenName,
                response.data.addition,
              );

              props.history.push('/console');
            }
          }
        } catch (e) {
          const errorMessage = e instanceof Error ? e.message : String(e);
          toaster.danger(
            t('signin:form_error_ssh_login') + ': ' + errorMessage,
          );
          if (window && window.parent) {
            window.parent.postMessage(
              {
                message: 'close',
              },
              '*',
            );
          }
          props.history.push('/');
        }
      })
      .catch((e: unknown) => {
        const errorMessage = e instanceof Error ? e.message : String(e);
        toaster.danger(t('signin:form_error_ssh_login') + ': ' + errorMessage);
        if (window && window.parent) {
          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;
