import { useEffect, useMemo } from 'react';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { FEATURE_FLAG_KEYS } from 'src/config/firebase';
import { isProd } from 'src/constants/env';
import { useFeatureFlag } from 'src/contexts/FeatureFlagsContext';
import { useAuth } from 'src/contexts/JWTContext';
import { useMobileLayout } from 'src/hooks/useMobileLayout';
import { useLokaliseTranslation } from 'src/utils/i18n';

import Tabs from 'src/components/tabs';

const LACOMER_INSTANCE_ID_PROD_REAL = 2387;
const LACOMER_INSTANCE_ID_PROD_TESTING = 2944;

const LACOMER_INSTANCE_IDS_PROD = [
  LACOMER_INSTANCE_ID_PROD_REAL,
  LACOMER_INSTANCE_ID_PROD_TESTING,
];

export const useLaComerCheck = () => {
  const { instance } = useAuth();
  const { id: instanceId } = instance!;
  return LACOMER_INSTANCE_IDS_PROD.includes(instanceId);
};

const LaComerContent = ({ url }: { url: string }) => (
  <iframe
    id="ptifrmtgtframe"
    name="TargetContent"
    title="Main Content"
    style={{ flex: 1, height: '100%', width: '100%' }}
    src={url}
  />
);

type Props = {
  isMobileWebView?: boolean;
};

export const LaComerDocuments = ({ isMobileWebView }: Props) => {
  const { t } = useLokaliseTranslation('documents');
  const { instance } = useAuth();
  const { id: instanceId } = instance!;

  const { value: externalUrlsConfig } = useFeatureFlag(
    FEATURE_FLAG_KEYS.DOCUMENTS_TAB_EXTERNAL_URLS,
  );

  const tabs = useMemo(() => {
    const externalUrls = externalUrlsConfig.find(
      externalUrl => externalUrl.instanceId === instanceId,
    );

    if (!externalUrls) return [];

    return externalUrls?.urls.map((url, index) => ({
      title: t(`lacomer_tab_${index + 1}`),
      id: index.toString(),
      content: <LaComerContent url={url} />,
    }));
  }, [externalUrlsConfig, instanceId, t]);

  useMobileLayout(isMobileWebView);

  useEffect(() => {
    const script = document.createElement('script');

    script.innerHTML =
      'try {document.domain = "lacomer.com.mx"; document = "lacomer.com.mx"} catch (ex) {}';

    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    };
  }, []);

  useEffect(() => {
    function reloadIframe() {
      const lacomerIframe = document.getElementById(
        'ptifrmtgtframe',
      ) as HTMLIFrameElement;
      if (!lacomerIframe) return;
      lacomerIframe.src = lacomerIframe.src;
    }
    const intervalId = setInterval(reloadIframe, 18 * 60 * 1000);

    return () => clearInterval(intervalId);
  }, []);

  return (
    <Stack sx={{ px: 3, py: 2, height: '100%' }}>
      <Typography
        color="textPrimary"
        variant="h5"
        component="h1"
      >
        {t('my_documents')}
      </Typography>
      <Tabs
        id="lacomer-tabs"
        tabsProps={{
          variant: 'scrollable',
          allowScrollButtonsMobile: true,
        }}
        tabPanelProps={{
          sx: { pt: 3, flex: 1 },
        }}
        tabs={tabs}
        withDivider
      />
    </Stack>
  );
};

export default LaComerDocuments;
