import { useEffect, useState } from 'react';

import {
  IconArrowsMaximize,
  IconArrowsMinimize,
} from '@material-hu/icons/tabler';
import Fab from '@material-hu/mui/Fab';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';

import useHuSnackbar from '@material-hu/components/design-system/Snackbar';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { useLokaliseTranslation } from 'src/utils/i18n';

export type ScormIframeProps = {
  src: string;
};

export const ScormIframe = ({ src }: ScormIframeProps) => {
  const [isFullScreen, setIsFullScreen] = useState(false);

  const { t } = useLokaliseTranslation('general');
  const { enqueueSnackbar } = useHuSnackbar();
  const { spacing, palette } = useTheme();

  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullScreen(!!document.fullscreenElement);
    };

    document.addEventListener('fullscreenchange', handleFullscreenChange);

    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, []);

  const handleFullScreen = () => {
    const scormContainer = document.getElementById('scorm-container');

    if (!scormContainer) return;

    if (!document.fullscreenElement) {
      scormContainer.requestFullscreen().catch(() => {
        enqueueSnackbar({
          title: t('full_screen.error'),
          variant: 'error',
        });
      });
    } else {
      document.exitFullscreen();
    }
  };

  const buttonLabel = isFullScreen
    ? t('full_screen.exit')
    : t('full_screen.title');

  const buttonIcon = isFullScreen ? (
    <IconArrowsMinimize />
  ) : (
    <IconArrowsMaximize />
  );

  return (
    <Stack
      id="scorm-container"
      sx={{
        position: 'relative',
        width: '100%',
        height: '400px',
      }}
    >
      <HuTooltip
        title={buttonLabel}
        direction="bottom"
      >
        <Fab
          color="primary"
          size="small"
          aria-label={buttonLabel}
          onClick={handleFullScreen}
          sx={{
            position: 'absolute',
            top: spacing(1),
            right: spacing(1),
          }}
        >
          {buttonIcon}
        </Fab>
      </HuTooltip>
      <iframe
        id="scorm-iframe"
        src={src}
        allowFullScreen
        title="Scorm-iframe"
        style={{
          width: '100%',
          height: '100%',
          border: '1px solid',
          borderColor: palette.new.border.neutral.divider,
          backgroundColor: palette.new.background.layout.default,
        }}
      />
    </Stack>
  );
};

export default ScormIframe;
