import i18next from '@config/i18n';
import {AiChatbotUserConfig, Instance} from '@interfaces/instance';
import {User} from '@interfaces/user';
import {COLORS} from '@shared/theme';
import {getCompleteName, isAndroid} from '@shared/utils';

export const CHATBOT_NAME = 'AI Chatbot';

export const ANIMATION_DURATION = 250;

export const KEYBOARD_OFFSET = isAndroid ? 16 : 40;

// Languages that are safe to use with btoa() (ASCII-compatible characters)
const BTOA_COMPATIBLE_LANGUAGES = [
  'en', // English
  'es', // Spanish (mostly safe)
  'fr', // French (mostly safe)
  'it', // Italian (mostly safe)
  'pt', // Portuguese (mostly safe)
];

// Get safe translations for chatbot (fallback to English for incompatible languages)
const getSafeTranslation = (key: string): string => {
  const currentLanguage = i18next.language || 'en';

  if (BTOA_COMPATIBLE_LANGUAGES.includes(currentLanguage)) {
    return i18next.t(key);
  }

  // Fallback to English for incompatible languages
  return i18next.t(key, {lng: 'en'});
};

// TODO: Pending style fixes
// Styles not applied to the User message bubble --> .vfrc-user-response .vfrc-message
// Styles not applied to the Input container (focus-within) --> .vfrc-input-container:focus-within
const getChatbotStyles = (instanceColor: string, isFullscreen: boolean) =>
  btoa(`
    .vfrc-header {
      background-color: ${instanceColor} !important;
    }
    .vfrc-header .vfrc-icon {
      color: ${COLORS.neutral} !important;
    }
    ${
      isFullscreen
        ? `
    .vfrc-header--actions .vfrc-header--button:last-child {
      display: none !important;
    }`
        : ''
    }
    .vfrc-user-response .vfrc-message {
      background-color: ${instanceColor} !important;
      color: ${COLORS.neutral} !important;
    }
    .vfrc-input-container:focus-within {
      border-color: ${instanceColor} !important;
    }
    .vfrc-prompt button.vfrc-button {
      color: transparent !important;
      position: relative;
    }
    .vfrc-prompt button.vfrc-button::after {
      align-items: center;
      color: ${COLORS.neutral} !important;
      display: flex;
      inset: 0;
      justify-content: center;
      position: absolute;
    }
    .vfrc-prompt button.vfrc-button[label='Start new chat']::after {
      background-color: ${instanceColor} !important;
      color: ${COLORS.neutral} !important;
      content: '${getSafeTranslation('general.restart_conversation')}';
    }
    .vfrc-prompt button.vfrc-button[label='Cancel']::after {
      background-color: ${COLORS.neutral} !important;
      color: ${instanceColor} !important;
      content: '${getSafeTranslation('general.cancel')}';
    }
  `);

// Test Bot: 67e463399257b4d69360e315
export const getChatBotHtml = ({
  aiChatbotConfig,
  user,
  instance,
  isFullscreen,
}: {
  aiChatbotConfig: Nullable<AiChatbotUserConfig>;
  user: User;
  instance: Instance;
  isFullscreen: boolean;
}) => `
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  </head>
  <body>
    <script type="text/javascript">
      (function(d, t) {
        var v = d.createElement(t), s = d.getElementsByTagName(t)[0];
        v.onload = function() {
          window.voiceflow.chat.load({
            verify: { projectID: '${aiChatbotConfig?.aiChatbotId}' },
            url: 'https://general-runtime.voiceflow.com',
            versionID: 'production',
            assistant: {
              stylesheet: 'data:text/css;base64,${getChatbotStyles(
                instance.color,
                isFullscreen,
              )}',
              persistence: 'localStorage',
            },
            autostart: true,
            userID: '${user.id}',
            launch: {
              event: {
                type: 'launch',
                payload: {
                  user_name: '${getCompleteName(user)}',
                  user_id: '${user.id}',
                  instance_id: '${instance.id}',
                  system_language: '${instance.language}',
                  user_segmentations: ${JSON.stringify(
                    aiChatbotConfig?.userSegmentationItemIdsByGroupId || {},
                  )},
                },
              },
            },
          }).then(() => {
            window.voiceflow.chat.open().then(() => {
              setTimeout(function () {
                window.ReactNativeWebView.postMessage('READY');
              }, 500);
            });
          });
        };
        v.src = "https://cdn.voiceflow.com/widget-next/bundle.mjs";
        v.type = "text/javascript";
        s.parentNode.insertBefore(v, s);
      })(document, 'script');
    </script>
  </body>
</html>
`;
