import { __ } from "@wordpress/i18n";
import { useState, useEffect } from "@wordpress/element";
import { Button, TextControl, Modal } from "@wordpress/components";
import { trash } from "@wordpress/icons";
import { createBlock } from "@wordpress/blocks";
import { useSelect } from "@wordpress/data";
import { store as blockEditorStore } from "@wordpress/block-editor";
import { getPatternsByCategory, saveBlockAsPattern, deletePattern } from "../../../core/customPatterns";
import { isPlus } from "../../../utils/is-pro";
import { getLocalizedUrl } from "../../../utils/localized-url";

/**
 * ブロックコメントからattributesを直接抽出する（parse()を使わない）
 * parse()はWordPressのバリデーションを実行し、save()の出力が変更された場合に
 * コンソールエラーを発生させるため、コメントからJSON抽出で回避する
 * @param content
 */
const extractBlockInfoFromComment = (content) => {
  const withAttrs = content.match(/<!--\s*wp:(\S+)\s+(\{.*?\})\s*-->/);
  if (withAttrs) {
    try {
      return {
        name: withAttrs[1],
        attributes: JSON.parse(withAttrs[2]),
      };
    } catch (e) {
      // JSON parse error
    }
  }
  const withoutAttrs = content.match(/<!--\s*wp:(\S+)\s*-->/);
  if (withoutAttrs) {
    return { name: withoutAttrs[1], attributes: {} };
  }
  return null;
};

const DefaultPreview = ({ attributes, previewDevice }) => {
  const bgColor = attributes.backgroundColorV2?.[previewDevice]?.color || attributes.backgroundColorV2?.pc?.color || "#2669e6";
  const textColor = attributes.textColor || "#ffffff";
  const radius = attributes.radiusV2?.[previewDevice]?.bulk || attributes.radiusV2?.pc?.bulk || 4;

  return (
    <div
      style={{
        backgroundColor: bgColor,
        color: textColor,
        borderRadius: `${radius}px`,
        padding: "12px 24px",
        textAlign: "center",
        fontSize: "14px",
        fontWeight: 500,
      }}
    >
      {attributes.content || "Button"}
    </div>
  );
};

const CustomPatternManager = ({ blockType, setAttributes, PreviewComponent = null }) => {
  const [patterns, setPatterns] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    loadPatterns();
  }, [blockType]);

  const loadPatterns = async () => {
    setIsLoading(true);
    const loadedPatterns = await getPatternsByCategory(blockType);
    setPatterns(loadedPatterns);
    setIsLoading(false);
  };

  const handleDeletePattern = async (patternId) => {
    if (!window.confirm(__("Delete this pattern?", "zenblocks"))) {
      return;
    }
    try {
      await deletePattern(patternId);
      await loadPatterns();
    } catch (error) {
      console.error("Failed to delete pattern:", error);
    }
  };

  const handleSelectPattern = (pattern) => {
    const content = pattern.content?.raw || pattern.content?.rendered || "";
    if (!content) {
      return;
    }

    const blockInfo = extractBlockInfoFromComment(content);
    if (blockInfo) {
      // createBlockでデフォルト値とマージし、正しいattributesセットを生成
      const block = createBlock(blockInfo.name, blockInfo.attributes);
      setAttributes(block.attributes);
    }
  };

  const getPatternAttributes = (pattern) => {
    const content = pattern.content?.raw || pattern.content?.rendered || "";
    if (!content) {
      return {};
    }
    const blockInfo = extractBlockInfoFromComment(content);
    return blockInfo ? blockInfo.attributes : {};
  };

  const getPatternHtml = (pattern) => {
    return pattern.content?.raw || pattern.content?.rendered || "";
  };

  if (isLoading) {
    return <div className="custom-pattern-loading">{__("Loading…", "zenblocks")}</div>;
  }

  const Preview = PreviewComponent || DefaultPreview;

  return (
    <div className="custom-pattern-manager">
      {patterns.length === 0 ? (
        <div className="custom-pattern-empty">
          <p>{__("No custom patterns yet", "zenblocks")}</p>
          <p>{__("Use the [+] button in the toolbar to save", "zenblocks")}</p>
        </div>
      ) : (
        <div className="custom-pattern-list">
          {patterns.map((pattern) => {
            const patternAttrs = getPatternAttributes(pattern);
            const patternHtml = getPatternHtml(pattern);
            return (
              <div
                key={pattern.id}
                className="custom-pattern-item"
                style={{
                  position: "relative",
                  marginBottom: "8px",
                }}
              >
                <div
                  className="custom-pattern-preview"
                  onClick={() => handleSelectPattern(pattern)}
                  style={{
                    cursor: "pointer",
                    overflowX: "auto",
                    paddingRight: "40px",
                  }}
                >
                  <Preview attributes={patternAttrs} html={patternHtml} previewDevice="pc" />
                </div>
                <Button
                  icon={trash}
                  isSmall
                  isDestructive
                  onClick={() => handleDeletePattern(pattern.id)}
                  label={__("Delete", "zenblocks")}
                  style={{
                    position: "absolute",
                    right: 0,
                    top: "50%",
                    transform: "translateY(-50%)",
                    flexShrink: 0,
                  }}
                />
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export const SavePatternButton = ({ blockType, clientId, onSaved, customIcon }) => {
  const [isSaveModalOpen, setIsSaveModalOpen] = useState(false);
  const [patternName, setPatternName] = useState("");
  const [isSaving, setIsSaving] = useState(false);
  const isPlusUser = isPlus();

  const block = useSelect(
    (select) => {
      if (!clientId) {
        return null;
      }
      return select(blockEditorStore).getBlock(clientId);
    },
    [clientId],
  );

  const handleSavePattern = async () => {
    if (!patternName.trim() || !block) {
      return;
    }

    setIsSaving(true);
    try {
      await saveBlockAsPattern(block, patternName.trim(), blockType);
      setPatternName("");
      setIsSaveModalOpen(false);
      if (onSaved) {
        onSaved();
      }
    } catch (error) {
      console.error("Failed to save pattern:", error);
      alert(__("Failed to save pattern", "zenblocks"));
    }
    setIsSaving(false);
  };

  return (
    <>
      <Button icon={customIcon || "plus"} onClick={() => setIsSaveModalOpen(true)} label={__("Save to Design Settings", "zenblocks")} />

      {isSaveModalOpen && (
        <Modal
          title={__("Save Pattern", "zenblocks")}
          onRequestClose={() => setIsSaveModalOpen(false)}
          className="zenblocks-save-pattern-modal"
          overlayClassName="zenblocks-save-pattern-modal-overlay"
        >
          {isPlusUser ? (
            <>
              <TextControl label={__("Pattern Name", "zenblocks")} value={patternName} onChange={setPatternName} placeholder={__("e.g. Favorite Button", "zenblocks")} />
              <p
                style={{
                  fontSize: "12px",
                  color: "#757575",
                  margin: "8px 0 16px",
                }}
              >
                {__("Category:", "zenblocks")} <strong>{blockType}</strong>
              </p>
              <div
                style={{
                  display: "flex",
                  gap: "8px",
                  justifyContent: "flex-end",
                }}
              >
                <Button variant="secondary" onClick={() => setIsSaveModalOpen(false)}>
                  {__("Cancel", "zenblocks")}
                </Button>
                <Button variant="primary" onClick={handleSavePattern} disabled={!patternName.trim() || isSaving} isBusy={isSaving}>
                  {__("Save", "zenblocks")}
                </Button>
              </div>
            </>
          ) : (
            <div style={{ textAlign: "center", padding: "20px 0" }}>
              <div
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  justifyContent: "center",
                  background: "#2563eb",
                  color: "#fff",
                  padding: "4px 12px",
                  borderRadius: "3px",
                  marginBottom: "12px",
                }}
              >
                <span
                  style={{
                    fontSize: "11px",
                    fontWeight: 700,
                    letterSpacing: "0.5px",
                  }}
                >
                  PLUS
                </span>
              </div>
              <p
                style={{
                  fontSize: "14px",
                  color: "#1e1e1e",
                  margin: "0 0 8px",
                }}
              >
                {__("Custom patterns require ZenBlocks Plus.", "zenblocks")}
              </p>
              <p
                style={{
                  fontSize: "13px",
                  color: "#757575",
                  margin: "0 0 20px",
                }}
              >
                {__("Save and reuse your favorite button designs.", "zenblocks")}
              </p>
              <a
                href={getLocalizedUrl("/downloads/")}
                target="_blank"
                rel="noopener noreferrer"
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  gap: "6px",
                  background: "#1e1e1e",
                  color: "#fff",
                  padding: "10px 20px",
                  borderRadius: "4px",
                  textDecoration: "none",
                  fontSize: "13px",
                  fontWeight: 600,
                }}
              >
                {__("Get ZenBlocks Plus", "zenblocks")} →
              </a>
              <div style={{ marginTop: "16px" }}>
                <Button variant="secondary" onClick={() => setIsSaveModalOpen(false)}>
                  {__("Close", "zenblocks")}
                </Button>
              </div>
            </div>
          )}
        </Modal>
      )}
    </>
  );
};

export default CustomPatternManager;
