import { useEffect, useImperativeHandle, useRef, useState } from 'react';
import { useFullscreen, useSize } from 'ahooks';
import IframeResizer from 'iframe-resizer-react';
import { useTheme } from '@mui/material';
import Chrome from './chrome';

export default function PaymentLinkPreview({
  ref = undefined,
  id,
  version = 1,
}: { id: string; version?: number } & {
  ref?: React.RefObject<unknown | null>;
}) {
  const theme = useTheme();
  const innerRef = useRef(null);
  const size = useSize(innerRef);
  const scale = (size?.width || 0) / 1280;
  const [mode, setMode] = useState(theme.palette.mode);
  const [fullscreen, { toggleFullscreen }] = useFullscreen(innerRef);

  useImperativeHandle(ref, () => ({
    ref: innerRef.current,
    fullscreen,
    toggleFullscreen,
  }));

  useEffect(() => {
    if (theme.palette.mode !== mode) {
      setMode(theme.palette.mode);
    }
  }, [theme.palette.mode, mode]);

  const iframeSrc = `${window.blocklet.prefix}checkout/pay/${id}?preview=1&version=${version}&theme=${mode}`;
  return (
    <div ref={innerRef}>
      {fullscreen ? (
        <div style={{ width: '100%', height: '100%', background: theme.palette.background.paper || '#fff' }}>
          <IframeResizer
            style={{ width: '100%', height: '100vh', overflow: 'hidden', border: 'none' }}
            src={iframeSrc}
          />
        </div>
      ) : (
        <Chrome sx={{ width: '100%', height: 800 * scale }}>
          <IframeResizer
            style={{
              width: '1280px',
              height: '800px',
              transform: `scale(${scale})`,
              transformOrigin: 'top left',
              border: 'none',
            }}
            src={iframeSrc}
          />
        </Chrome>
      )}
    </div>
  );
}
