import { Group, Image as KonvaImage, Rect, Text as KonvaText } from 'react-konva';
import useImage from 'use-image';

function TemplateImage({ src, x, y, width, height, opacity = 1, listening = false }) {
  const [img] = useImage(src, 'anonymous');
  return <KonvaImage image={img} x={x} y={y} width={width} height={height} opacity={opacity} listening={listening} />;
}

function TemplateText({ text, x, y, fontSize, fontFamily, fill, rotation = 0 }) {
  return <KonvaText text={text} x={x} y={y} fontSize={fontSize} fontFamily={fontFamily} fill={fill} rotation={rotation} listening={false} />;
}

export function TemplateLayer({ template, canvasSize = 300 }) {
  if (!template) return null;
  const { background, overlay } = template;

  return (
    <Group name="template-layer">
      {background && (
        <Group name="template-background">
          {background.type === 'color' ? (
            <Rect x={0} y={0} width={canvasSize} height={canvasSize} fill={background.color} listening={false} />
          ) : background.type === 'image' ? (
            <TemplateImage src={background.src} x={0} y={0} width={canvasSize} height={canvasSize} listening={false} />
          ) : null}
        </Group>
      )}
      {overlay && overlay.map((el, index) => {
        if (el.nonPrintable) return null;
        const key = `overlay-${index}`;
        if (el.type === 'image') return <TemplateImage key={key} src={el.src} x={el.x || 0} y={el.y || 0} width={el.width || 100} height={el.height || 100} opacity={el.opacity} listening={false} />;
        if (el.type === 'text') return <TemplateText key={key} text={el.text} x={el.x || 0} y={el.y || 0} fontSize={el.fontSize} fontFamily={el.fontFamily} fill={el.fill} rotation={el.rotation} />;
        return null;
      })}
    </Group>
  );
}
