import { useLayoutEffect, useRef, useState } from 'react';

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

import { CertificateType } from 'src/pages/dashboard/Learning/Settings/Certificates/constants';

import ClassicTemplate from './ClassicTemplate';
import CustomTemplate from './CustomTemplate';
import ModernTemplate from './ModernTemplate';
import { CERTIFICATE_DESIGN_WIDTH } from './shared/constants';
import { canvasContainerSx, getCanvasInnerSx } from './shared/shared.styles';
import { type CertificatePreviewProps } from './types';

const TEMPLATE_COMPONENTS = {
  [CertificateType.CLASSIC]: ClassicTemplate,
  [CertificateType.MODERN]: ModernTemplate,
  [CertificateType.CUSTOM_BACKGROUND]: CustomTemplate,
} as const;

const CertificatePreviewCanvas = (props: CertificatePreviewProps) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [scale, setScale] = useState(1);

  useLayoutEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const update = (width: number) => {
      if (width > 0) setScale(width / CERTIFICATE_DESIGN_WIDTH);
    };

    update(container.offsetWidth);

    const observer = new ResizeObserver(([entry]) => {
      update(entry.contentRect.width);
    });
    observer.observe(container);
    return () => observer.disconnect();
  }, []);

  const TemplateComponent =
    TEMPLATE_COMPONENTS[props.templateId] ??
    TEMPLATE_COMPONENTS[CertificateType.CLASSIC];

  return (
    <Stack
      ref={containerRef}
      sx={canvasContainerSx}
    >
      <Stack sx={getCanvasInnerSx(scale)}>
        <TemplateComponent {...props} />
      </Stack>
    </Stack>
  );
};

export default CertificatePreviewCanvas;
