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) => {
      console.log('Signin.tsx - Message received:', event);
      console.log('Origin:', event.origin);
      console.log('Data:', event.data);

      // Validar que el mensaje tenga los datos necesarios
      if (!event.data || typeof event.data !== 'object') {
        console.log('Signin.tsx - Invalid message format');
        return;
      }

      // Validar origen: REACT_APP_CLUSTER_URL debe estar contenido en el origen recibido
      const clusterUrl = process.env.REACT_APP_CLUSTER_URL;

      if (!clusterUrl) {
        console.log(
          'Signin.tsx - REACT_APP_CLUSTER_URL not configured, rejecting message',
        );
        return;
      }

      // Normalizar origen: quitar protocolo y puerto para comparación flexible
      const normalizeOrigin = (url: string) => {
        try {
          // Si ya es una URL completa, extraer el hostname
          if (url.includes('://')) {
            const urlObj = new URL(url);
            return urlObj.hostname.toLowerCase();
          }
          // Si es solo hostname, devolverlo en lowercase y limpiar
          return url
            .toLowerCase()
            .replace(/^https?:\/\//, '')
            .replace(/:\d+$/, '')
            .split('/')[0]
            .trim();
        } catch {
          // Si falla el parsing, intentar limpiar manualmente
          return url
            .toLowerCase()
            .replace(/^https?:\/\//, '')
            .replace(/:\d+$/, '')
            .split('/')[0]
            .trim();
        }
      };

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

      console.log('Signin.tsx - Origin validation:', {
        originalOrigin: event.origin,
        normalizedOrigin: originHostname,
        originalClusterUrl: clusterUrl,
        normalizedClusterUrl: clusterHostname,
      });

      if (originHostname !== clusterHostname) {
        console.log(
          'Signin.tsx - Origin not allowed:',
          event.origin,
          '(normalized:',
          originHostname,
          ')',
          'Expected:',
          clusterUrl,
          '(normalized:',
          clusterHostname,
          ')',
        );
        return;
      }

      console.log(
        'Signin.tsx - Origin allowed:',
        event.origin,
        'Matches:',
        clusterUrl,
      );

      // Verificar que el mensaje tenga los campos necesarios
      if (event.data.host && event.data.username && event.data.password) {
        console.log('Signin.tsx - Valid message received, processing...');
        doSignin(event.data);
      } else {
        console.log('Signin.tsx - Message missing required fields');
      }
    };

    window.addEventListener('message', handleMessage);

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

  const { t } = useTranslation(['signin']);
  const doSignin = (data: Record<string, string>) => {
    console.log('Signin.tsx - Received data:', data);

    // Normalizar datos recibidos (lowercase, trim)
    const normalizedData = {
      host: String(data.host || '')
        .toLowerCase()
        .trim(),
      port: String(data.port || '22').trim(),
      username: String(data.username || '').trim(),
      passwd: String(data.password || '').trim(),
    };

    console.log('Signin.tsx - Normalized data:', {
      ...normalizedData,
      passwd: '***',
    });

    // Validar que todos los campos requeridos estén presentes
    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) => {
        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', 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);
          console.log(errorMessage);
          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: unknown) => {
        const errorMessage = e instanceof Error ? e.message : String(e);
        console.log(errorMessage);
        toaster.danger(t('signin:form_error_ssh_login') + ': ' + errorMessage);
        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;
