import { useState, useRef } from "@wordpress/element";
import { serialize } from "@wordpress/blocks";
import { createBlock } from "@wordpress/blocks";

const PREVIEW_MAX_WIDTH = 240;

const getButtonWidth = (attributes) => {
  if (!attributes?.layoutWidthV2?.pc) return null;
  const pc = attributes.layoutWidthV2.pc;
  
  if (pc.unit === "fit-content" || pc.unit === "%" ) {
    if (pc.maxUseCustom && pc.maxValue) {
      return `${pc.maxValue}${pc.maxUnit || "px"}`;
    }
  }
  
  if (pc.useCustom && pc.value && pc.unit && pc.unit !== "fit-content" && pc.unit !== "%") {
    return `${pc.value}${pc.unit}`;
  }
  
  if (pc.maxUseCustom && pc.maxValue) {
    return `${pc.maxValue}${pc.maxUnit || "px"}`;
  }
  
  if (pc.minUseCustom && pc.minValue) {
    return `${pc.minValue}${pc.minUnit || "px"}`;
  }
  
  return null;
};

const ButtonPatternPreview = ({ attributes, html }) => {
  const [isHovered, setIsHovered] = useState(false);
  const containerRef = useRef(null);

  const buttonWidth = getButtonWidth(attributes);
  const isFitContent = attributes?.layoutWidthV2?.pc?.unit === "fit-content";
  const hasCopyMicro = !!attributes?.copyMicro;
  const hasCopySub = !!attributes?.copySub;
  let previewHtml = html || "";

  if (!previewHtml && attributes) {
    try {
      const block = createBlock("zenblocks/button-basic", attributes);
      previewHtml = serialize(block);
    } catch (e) {
      previewHtml = "";
    }
  }

  if (previewHtml) {
    const commentMatch = previewHtml.match(/^<!--[\s\S]*?-->\s*/);
    if (commentMatch) {
      previewHtml = previewHtml.slice(commentMatch[0].length);
    }
    const endCommentMatch = previewHtml.match(/\s*<!--[\s\S]*?-->$/);
    if (endCommentMatch) {
      previewHtml = previewHtml.slice(0, -endCommentMatch[0].length);
    }
  }

  const wrapperStyle = {
    maxWidth: `${PREVIEW_MAX_WIDTH}px`,
    overflowX: "auto",
    overflowY: "visible",
    cursor: "pointer",
    paddingTop: hasCopyMicro ? "18px" : 0,
    paddingBottom: hasCopySub ? "12px" : 0,
  };

  const scaledContainerStyle = {
    pointerEvents: "auto",
    display: "inline-block",
    whiteSpace: "nowrap",
    ...(buttonWidth && { width: buttonWidth }),
  };

  const hoverClass = isHovered ? "force-hover" : "";
  const fitContentClass = isFitContent ? "is-fit-content" : "";

  return (
    <div
      style={wrapperStyle}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      <div
        ref={containerRef}
        style={scaledContainerStyle}
        className={`button-pattern-preview-inner ${hoverClass} ${fitContentClass}`}
        dangerouslySetInnerHTML={{ __html: previewHtml }}
      />
    </div>
  );
};

export default ButtonPatternPreview;
